Click here to Skip to main content
15,885,278 members
Everything / Programming Languages / Razor

Razor

Razor

Great Reads

by Pete O'Hanlon
Rather than littering a razor component with @if (a == b) logic to show items, use render fragments to make a declarative component
by Ken Haggerty
Scaffold and modify Identity in the new ASP.NET Core 2.2 Razor pages template
by Coding Notes
An introduction to ASP.NET Core MVC
by Ajcek84
Implementation of radar chart for various .NET platforms

Latest Articles

by Victor Sirghii
On the parent razor page, we add Partial View which will serve as the updatable container. On Ajax calls from the parent page, we update only Partial view content, not the whole page, thus creating a smooth user interaction experience.
by Jani Giannoudis
Structured approach to ASP.NET Localization
by Pete O'Hanlon
Rather than littering a razor component with @if (a == b) logic to show items, use render fragments to make a declarative component

All Articles

Sort by Score

Razor 

26 Jun 2023 by Pete O'Hanlon
Rather than littering a razor component with @if (a == b) logic to show items, use render fragments to make a declarative component
22 Dec 2018 by Ken Haggerty
Scaffold and modify Identity in the new ASP.NET Core 2.2 Razor pages template
9 Mar 2022 by Coding Notes
An introduction to ASP.NET Core MVC
23 Jul 2018 by Ajcek84
Implementation of radar chart for various .NET platforms
9 Jan 2013 by Adrian Holland
JSRazor brings the power of razor-like templates to client-side javascript.
30 Oct 2018 by Leonard E. James
Create initial object model and database and display first Razor Page
31 May 2012 by Prasad_Kulkarni
Please refer: Telerik Extensions for ASP.NET MVC ManualUsing with the Razor View Engine[^]MVC with Razor & aspx[^]
11 Oct 2012 by Sergey Alexandrovich Kryukov
You need to find some service which provides the ZIP code lookup. As I can see from your profile, you are in U.S., right? So, it could be like this one:http://www.zip-codes.com/search.asp[^].It would be more convenient to get a service with is provided as a Web service. Here is...
4 Mar 2014 by Snesh Prajapati
Try this: @Html.TextBoxFor(x => x.Name, new { Id="txtName" })In your Script part, try with this: $("#txtName").change(function () { var name = $("#txtName").val(); alert(name); });
30 Mar 2014 by Sergey Alexandrovich Kryukov
Not only you did not show where the exception with the message "Object reference not set to an instance of an object" is thrown, you did not even show any code. How do you think anyone could help you to fix the problem? You cannot ask such questions every time you face with such situations; you...
3 Mar 2016 by Patrice T
Quote:I am trying to append More than Million record to listBox. Absolutely avoid this.There is no solution to fast add a million lines to listbox.You have to find another way that fit the needs.Think about what append when you search on facebook or google: you begin to type something...
6 Mar 2012 by Gianmaria Gregori
Using an upload plugin with progress bar in Razor pages
11 Mar 2012 by Gianmaria Gregori
Additions to the implementations of the Uploadify plugin in Webmatrix
18 Jun 2012 by DaveAuld
Quick way to modify the logon view depending on if the user has been redirected.
18 Jul 2012 by Christian Graus
You are confused. AJAX and jQuery are not contradictions, they are two complementary things. You should use jquery to make AJAX calls. AJAX cannot show your popup, but it is the ONLY way to contact the server without refreshing your page.As someone else said, there are a number of jquery...
24 Aug 2012 by Christian Graus
We use tinyMCE[^] in our MVC3 application, it's a HTML editor. Here[^] is a HTML rich text editor. We used tinyMCE in asp, ASP.NET and MVC3. There's no reason you can't use any existing component in your MVC3 site.
6 Sep 2012 by Syed Salman Raza Zaidi
Use: @model IEnumerableon top of your view,as you're having IList so you'll have to specify model as IEnmumerable
30 Oct 2012 by Member 9359591
htmlvar account = document.getElementById('account');var changed = document.getElementById('account_changed');changed.value = new Array(account.value.length-3).join('x') +...
6 Nov 2012 by jim lahey
You don't need to write any code, it's already been done:http://captchamvc.codeplex.com/[^]
11 Jul 2013 by Priyanka7777
Try: Session["UserID"] = UserID;
11 Jul 2013 by vinayakJJ
// storing value in sessionstring firstName = "Jeff";Session["FirstName"] = firstName;//reading value from sessionstring firstName = (string)(Session["FirstName"]);
12 Sep 2013 by Mehdy Moini
Why don't you use roles? you can define roles base on users kind, and limit controllers on role
11 Jan 2014 by Sampath Lokuge
You can use TempData for that.Note:Below example has been extracted from my Blog Article.So please Change it according to your scenario. Model:public class CreditCardInfo{ public string CardNumber { get; set; } public string Span { get; set; } public int ExpiryMonth...
2 Apr 2014 by Guruprasad.K.Basavaraju
You will have to use something like below. Just get the right Data item in place of lstTrxn.ID, also if you could post the Model details we can refine this solution@Html.ListBox("ListTrxn", Model.Select(item => new SelectListItem { Text = item.lstTrxn.ID.ToString() }), new {@class=...
3 Apr 2014 by Guruprasad.K.Basavaraju
You may want to use something like thismodel.txtFrmDate=System.DateTime.Today.ToShortDateString()
7 May 2014 by NKHari
I got the solution.....Thanks for the response everyone. @Html.DropDownListFor(model => item.Data.CategoryID, new SelectList((IEnumerable)ViewData["categories"], "CategoryID", "CategoryName", item.Data.CategoryID),"-Select Category-", new { @id = "category" + i })Declaring select list...
8 Sep 2014 by Sergey Alexandrovich Kryukov
In what you have observed, there was no such thing as "metadata classes". (Such concept does exist, but this is not what you have been looking at.) You faced completely different thing: you tried to see the declaration of .NET types without having the source code. The source code is simply not...
9 Nov 2014 by Suraj Sahoo | Coding Passion
I agree, if ActionLink is used why there is any need to add button tag. If there is a need to have button style, then only @Html.ActionLink("Home", "Index", "Home",new{@class="Name"}) add a class that has the css for a similar looking button, else the second approach does the job Sir....
24 Nov 2014 by Suraj Sahoo | Coding Passion
Quote:I don't have fixed Database Design ,i may modify existing table may add new table .As you say here, I anticipate you already have a database and may be you need modification in there in future. So I would suggest to opt for Database first approach. As you just need to add your database...
24 Nov 2014 by Sandeep Singh Shekhawat
Hi,The ADO.NET Entity Framework allows developers to choose any one approach among three possible approaches: Database First, Model First and Code First.Database First: It is a more data-centric design that is based on an existing database. The Entity Framework is able to generate a...
12 Sep 2015 by Ibrahim ben Salah
This tip talks about a new way of rendering the Razor template (cshtml files) using Xania.AspNet.Simulator.
23 Sep 2015 by F-ES Sitecore
You can't stop people using dev tools etc, the solution to your problem is to use html and http properly. If you want the total amount field to be one you control and not the user, then that's what you do. Show it as a label or text rather than a textbox. In your form actions when you want...
17 Jul 2016 by F-ES Sitecore
It's probably there (this is a guess) because the view code doesn't know what type ViewBag.Albums is at compile time (because ViewBag is a dynamic object) so the view won't compile if you try and loop through something that can't be looped through. By putting "as IEnumerable" it is going to...
20 Jul 2016 by Shmuel Zang
You can add the link's HTML to your string and, display it using the Html.Raw method. Something like:@{ string msg1 = "My Text My link."; @Html.Raw(msg1)}
5 Aug 2016 by F-ES Sitecore
@if (KeyValuePairList.TryGetValue("Key01", out TempValue)) { @TempValue @KeyValuePairList.Remove("Key01")}else { @:Value0001}The "@" means to render the output, so you are rendering the output of KeyValuePairList.Remove, which returns True if something has been removed, so...
26 Jun 2017 by David_Wimbley
Your issue is with the how model binding in MVC handles complex objects for use in the HTML helpers which is what you have going on in your view. Since you didn't post your model, I am guessing your model looks something like public class CountryLanguageModel { public CountryLanguage...
6 Jul 2017 by Richard Deeming
You need to pass the selected values to the MultiSelectList[^] constructor. It would also be more correct to use the ListBoxFor method, since you're not rendering a drop-down list. @Html.ListBoxFor(model => model.SelectedValues, new MultiSelectList(Models.GetCategoryList().OrderBy(c =>...
21 Sep 2017 by Vaidhya.P
Steps to Apply a Bootstrap theme, Step 1 : Copy all the Css and Java scripts inside the application. Step 2 : Then add the related css files and java script files in the bundle.config like the below code. Scripts: //-------------- jQgrid ---------------- ...
22 Dec 2018 by Ken Haggerty
Scaffold and modify Identity in the new ASP.NET Core 2.2 Razor pages template
31 Jul 2021 by Matthew Dennis
I found the videos at Blazor Train[^] to be very useful when trying to understand Blazor. Nice bite sized chunks of focused information. Also you might check out Chris Sainty - Building with Blazor[^]. He is literally writing the book.
25 Jan 2022 by Richard Deeming
Use the tag helper instead of the PartialFor extension method: @Model EditForm ...
18 Sep 2022 by towaso
A short example on how to create a hierarchical web checklist
18 Jun 2023 by Richard Deeming
Here's a nice example of creating a tree view in pure HTML and CSS - you don't even need any JavaScript: Tree views in CSS[^] Adapting that to add checkboxes to each item is fairly simple: ...
20 Jun 2023 by Sandeep Mewara
First off, launchSettings.json file is only used within the local development machine. Refer: ASP.NET Core launchSettings.json File - Dot Net Tutorials[^] Now, to setup a startup page for ASP.NET Core webapp, there are various ways: 1. Method...
29 Nov 2011 by Eduard Keilholz
Oh wow,I just found the answer somewhere online. You need to replace the 'minus' with an underscore.@using (Html.BeginForm("passwordchange", "account", FormMethod.Post, new { @class = "async", data_success = "account.passwordChangeSuccessfull();" }))This will do the trick!
13 Feb 2012 by Christian Graus
Your code does not check return values any step of the way. You need to do that, so it will never blow up. Then you need to look at the line that is blowing up, work out what object is null and read the documenation for the method that returned it, so you can work out what is going on. One...
10 Jun 2012 by Zoltán Zörgő
I have googled for it, and it turned out, that border-radius wont work with (some) input elements in IE9. It is a bug in the CSS3 engine or the problem lies in the fact, that these elements in IE are rather API level controls. Other browser developers have rewritten them from the scratch. I have...
9 Jul 2012 by Sandeep Mewara
Have a look at this blog entry: How to render MVC View on a Modal Popup Window[^]
20 Jul 2012 by Christian Graus
Oh, I see. You have arbitrary data you want to pass with AJAX ? I think the issue is that AJAX is not the right way to do a download. If you do a full post to a URL that returns a file, your page won't refresh, it will download the file. An AJAX call will return data to your javascript, which...
2 Aug 2012 by Christian Graus
Is this your ViewModel ? The easiest way to do this with MVC3, is to use the @Html.XXXFor methods to create appropriate controls to show your data, and then it will populate them on postback. I prefer to use AJAX and JSON, in which case you build your objects in javascript, but if you are happy...
22 Aug 2012 by Karthik. A
Check the following SO link:http://stackoverflow.com/questions/2998247/asp-net-mvc-html-textbox-set-autofocus-property[^]Else, in case you are using jQuery, you could simply do,$('.name_form').focus();Hope this helps!
8 Sep 2012 by suhas.shiv
Custom CheckBoxList in ASP.NET MVC3
10 Oct 2012 by DaveAuld
The simplest option is just to use javascript to copy across; Textbox 1 (FirstName):
11 Oct 2012 by Karthik. A
Here is a high level implementation of what you needed. Modify as per your need ! You have already gotten halfway!!http://jsfiddle.net/FTHRn/[^]Hope this helps!
28 Oct 2012 by Unsy
Hi GuysI'm trying to find a way to use some kind of autocomplete on a textbox in a view that is bound to a model. @Html.TextBoxFor(model => @Model.CaseContact.Company)I have found plenty of articles that point jQuery at a textbox control, but nothing on a bound MVC control.I...
9 Nov 2012 by Santhosh23
Hi All,How to set the default button on press enter key. not working my jquery script code.my code like this. @* $(document).ready(function () { $("#MyForm").keypress(function (e) { kCode = e.keyCode...
10 Dec 2012 by adama74
I'm also working on a similar task - mine is to extract test-nodes from html/cshtml/aspx/etc. type files.So far, I am using the HtmlAgilityPack to parse the HTML - but how to distinguish Razor markup from plain-text during parsing - THAT is the question.I haven't tried it out yet, but one...
10 Dec 2012 by Philippe Mori
I think that you are trying to use the wrong tool for the job...It make no sense to parse razor code to modify it. Use master pages, html helpers or maybe your own sequence that you would scan. Or better, why not uses razor itself to generate your code?You simple need to add in your...
22 Dec 2012 by Abhishek Pant
Change .cshtml to .aspx. Do not use the Razor engine.and this thead is for you-Allow Design View for MVC3 and Razor View Engine [^]I hope it solves your question.
2 Jan 2013 by Zoltán Zörgő
I have currently no access to your link, but you can use several kind of grids on mvc too. There are free, and commercial ones too. There is a good collection of them: http://stackoverflow.com/questions/177275/grid-controls-for-asp-net-mvc[^]
29 Jan 2013 by Sandesh M Patil
Refer below linkhttp://stackoverflow.com/questions/8275384/mvc3-page-ispostback-like-functionality[^]http://stackoverflow.com/questions/777179/asp-net-mvc-is-ispostback-still-here[^]
27 Feb 2013 by Sergey Alexandrovich Kryukov
This is not really encoding. Both strings are equivalent, but in first case, HTML characters are escaped by character entities. Please see:http://en.wikipedia.org/wiki/Character_entity[^],http://www.w3.org/TR/REC-html40/sgml/entities.html[^].Escaping and unescaping in JavaScript:...
7 Mar 2013 by Gianmaria Gregori
In case something else is interested to the solution of this answer, Mike Brind answered to this thread: How Can i allow users belongs to role only to access files in folder?[^].
24 Apr 2013 by Christoph Keller
Hi,This normally occures if you try to post a form in an IFrame and the result is JSON (mostly used in Ajax-fileuploads.The problem is (in the above mentioned scenario) that IE does not detect the JSON result as a text to display, so it assumes that you want to download it.To...
10 Jun 2013 by John-ph
This code sample is about using crystal report in asp.net MVC project.[^]. Check if it helps.
23 Jun 2013 by Zoltán Zörgő
In your select you defined anonymous objects. That's good, but than you pass the enumeration of anonymous objects to dynamic one that is passed to the view engine. The dynamic one has knowledge over it's fields so @ViewBag.BinStock will work. But the items in it are just anonymous objects -...
28 Jun 2013 by RomilGandhi
You can also do it by alternate way,follow this one public class Country{ [Required] public int CountryId { get; set; } public string CountryName {get;set:}}Controllerpublic ActionResult CountriesDropDown(){ using(ctx) { var dropdown = (from q in...
11 Jul 2013 by Nirav Prabtani
Assign value to Session after successful loginSession["UserID"] = value;here value can be anything like static or variable from Database....:)like Session["UserID"] = 10;orSession["UserID"] = Convert.toint32(DataTable1.Rows[0]["UserID"]);
16 Jul 2013 by abbaspirmoradi
Ok.I find Answer.I use this and my problem is solved.@Html.Raw(Model.Text)But I do not delete this question for guys that have such problem.
9 Sep 2013 by Jameel VM
I have created an sample which works fine.Please try like that public class TestController : Controller { // // GET: /Test/ public ActionResult Index() { ViewBag.StatusList = ...
9 Sep 2013 by Member 10262527
Hello , i am working on MVC application using razor views. i need to get the menu items on home page based on the users who logged into the site. So i wrote a store proc and accessing it in controller and getting list of menu items assigned to the log-in user. Now how do i map this list...
20 Sep 2013 by Mehdy Moini
If you want to call a action result which return a partial view you can use Html.RenderAction()http://www.dotnet-tricks.com/Tutorial/mvc/Q8V2130113-RenderPartial-vs-RenderAction-vs-Partial-vs-Action-in-MVC-Razor.html[^]
25 Jul 2022 by Adam Jones
How Can i make the EditorFor input disabledi have tried using the below which doesn't work@Html.EditorFor(model => model.TaskName, new { disabled = "disabled", @readonly = "readonly" })
26 Sep 2013 by Eduard Keilholz
I Posted an article about this yesterday :Storing binary data in SQL Server using EF[^]This will totally fit your needs.
28 Sep 2013 by Sampath Lokuge
I have completed same steps which you have mentioned.But no run time errors.It's working.So try again with new project on new place.Good luck.Quote:First I created an empty ASP.NET MVC 4 projectSecond I used Package Manager Console and typed;install-package twitter.bootstrap.mvc4...
3 Oct 2013 by FoxRoot
Hello everyone,I am developing a mvc4 application. I am in trouble using models in view. Let me explain the stracture.I have a model class that operates some methods and returns something. The name is KisiBLL.csI have a Controller class. That checks the actions. KisiController.csAnd...
3 Oct 2013 by Jameel VM
You should create a viewModel. ViewModel is nothing but a csharp class which contain whatever the data's displayes in one view. For example first of all create a class which contain all the properties in the kisi model class needed in the view . public class SampleViewModel{public...
23 Oct 2013 by thatraja
Hereafter don't include multiple unrelated questions while posting questions.Quote:Don't Answer as links directly give some information as Answer to my questionsOK, I'll tryQuote:1)What is Razor is it having any relation with java script?Yes, Razor is a View. You could include javascript...
4 Nov 2013 by sushil_gupta
I solved the problem. Below is the sample code. columns.Bound(a => a.Flag).ClientTemplate( "# if(Flag == 'Value1') { #" + " class='info k-button k-button- icontext' onclick='clickhere(#=parameter1#)' value='ClickHere' />" + "# } else { #" + "NormalText" + ...
24 Nov 2013 by mrbonny7
Hello,I am working an MVC3 application where I need to make use of the MVC Grid.Now as I am not abale to bind my datatable with the MVC grid. beloow is the controller code using which I am displaying certain data in the pages. It has a model name PartyHomeModel. There's a datatable in the...
18 Dec 2013 by Member 10434230
First of all it is very bad to have html elements with same ID, simply not accepted!!!In your case, you can make the id distinct by easily appending the row index... and same can be done with submit button... Now when you have a submit click you can take the id of control causing form submit,...
1 Jan 2014 by Nelek
Sure,for general purposehttps://www.google.de/#q=facebook%20programing[^]There you can find:https://developers.facebook.com/[^]http://www.phpeveryday.com/articles/Facebook-Programming-Facebook-Platform-P845.html[^]http://stackoverflow.com/questions/tagged/facebook[^]and many...
23 Jan 2014 by arindamrudra
Just give the same name to the checkbox like for all you should use below.Now when you are submitting the page, just use the FormCollection and use the key...
27 Feb 2014 by Member 3027893
I want the existing EnquireNow.cshtml View to be rendered on a JQuery-UI dialog on click of a link named 'Enquire Now' on my ProductDetails page.Following is the snapshot of the ProductDetailspage.$(function () { $('#dialogbox').dialog({ ...
7 Mar 2014 by Member 10587385
public static List getplinks() { List plinks = new List(); using (crbt_onwebEntities dbContext = new crbt_onwebEntities()) { plinks = (from z in dbContext.CRBT_Promotion select...
7 Mar 2014 by Sampath Lokuge
First, implement IPagable in any viewmodel that you have in your project that you want to enhance with Pagination functionality.namespace ar.com.juanpabloibanez.Samples.ViewModels{ public class SearchProducViewModel : IPageble { public SearchProducViewModel() ...
24 Mar 2014 by Alem.B
Hi!I have some difficult time to pass data to Partial view httpPost ActionResult method in Controller.Let me explain:1.Have entity which i have been generated with Entity Framework ORM and this looks like this.
30 Mar 2014 by Abhinav S
This error occurs when you access a property of an object that is null.As a basic step, ensure you check for nulls before accessing properties of objects.This however, may suppress the error butmay not help you solve the problem.For this ensure, your connection is correctly...
31 Mar 2014 by Guruprasad.K.Basavaraju
In your view change the IEnumerable to List, that solved a similar issue I had.@model ListIEnumerables are readonly.
5 Apr 2017 by Arvind Gaud
how To Add new Row on Textbox onchange which is into webgrid..my Jquery Code is --$(document).ready(function () { $('#txtpercentage').change(function () { alert('in') debugger var newRow = "
1 May 2014 by Sanket Saxena
$(function () { $("#chkrmark").first().focus(); });or $(function () { $("#chkrmark")[0].focus(); });
2 Jun 2014 by Member 2706889
How about you use the actual Razor template engine to do the job for you.Make sure you haveusing System.Web.Razor;and then something like thatRazorEngineHost _host = new RazorEngineHost(new CSharpRazorCodeLanguage());RazorTemplateEngine templateEngine = new...
5 Jun 2014 by John Sathish Tamilarasu
Hi all,I want update a Partial view on dropdown change using Jquery Ajax. The dropdown is in my partial view. Here i have mentioned the code used. But there is no change in the view. Kindly give your valuable suggestion.View :@model MyModels.CustomerDetailsModel@{ var val =...
5 Jun 2014 by Sampath Lokuge
Please try it without the dataType and contentType on Ajax method. :)function ddlChange() { var check = @Html.Raw(val); $.ajax({ async: false, url: '/Main/LoadddlView', data: '{model:' + JSON.stringify(check) + '}', type:...
20 Jun 2014 by Nathan Minier
There are a number of approaches that you can take. I'm going to show the POCO route, since that's how I approach MVC.First I would make sure that the dataOffender class has a 1:M link to the charges object:public class dataOffender{ [Key,...
23 Jun 2014 by Lalit Jankiram Sonawane
Use only reportViewerExample folder from below link,https://github.com/ilich/MvcReportViewerInstall the missing references using online nuget packages. Configure values for your server paths,credential in web.config (Some keys are already added in web.config after installation), also...
24 Jul 2014 by Yogesh Kumar Tyagi
view this article it may help youhttp://www.c-sharpcorner.com/UploadFile/3d39b4/casecading-dropdown-list-with-mvc-linq-to-sql-and-ajax/[^]
9 Aug 2014 by pourmoi
i'm a beginner in asp.net mvc 4 and i tryin to fill dropdownlist from database i'don't want to use entity for some raisins plz, can anybody help me with this :Medel :Client.cspublic class Client { public int ClientID { get; set; } public string Nom { get; set; } ...