While using Html Helpers in Views. If I try to write a lambda expression like "m=>...." . Small m automatically changes into "Model". It usually happens If I choose helper without "For" word in it. like DropdownList insted of DropdownListFor . Also if I use any other letter for lambda expression it changes into something else.
And m=>m.name and Model.name also gives the same result if I am not wrong.
Why?
If you do something like this:
#Html.TextBoxFor(m => m.Name)
And this:
#Html.TextBoxFor(Model => Model.Name)
In Asp.Net MVC at Views, we have a property called Model, which access the Model (capital M) you are getting from the controller. It is case sensitive.
Html Helper without the For word in the name like Html.TextBox() or Html.DropDownList() are helpers to generate html tags for any other field that is not in the model. Actually, in the first version of asp.net mvc, we did not have the strongly typed view, so, we could not have the Html.TextBoxFor for sample, so, we used to use this weakly helpers.
Out of the ontext of MVC, in terms of lambda expression, the name of argument does not matter.
that happens because of intellisense of visual studio.DropDownList expects you to supply a parameter that is string not lambda expression. When you try to enter lambda expression it chooses one of the word in the intellisense list. For example if you write b and enter = it automatically gonna change it to base=. To use lambda expression use DropDownlistFor.
Related
I've always followed the intended convention of using the parameter for model binding in ASP.Net MVC Razor "-For(..)" helpers. I know that the parameter is the view's model (the Model property). But what are the potential side effect of binding to the Model property instead?
In other words, what are the consequences of, ..
instead of this ..
#Html.TextBoxFor(m => m.MyProperty)
.. doing this instead?
#Html.TextBoxFor(m => Model.MyProperty)
I understand if I put #model Product in my view then in the expression #Html.TextBoxFor(x => x.ProuctId) the type of type lambda is Func<Product, int>. I can understand how the framework uses the lambda to get the value simply by just calling it but how does it get the string "ProductId" to use in the for the id and name properties of the input that is rendered? Can this somehow be obtained using reflection, if so how?
I've just noticed that the type of the parameter for TextBoxFor is actually Expression<Func<Product, int>> so am guessing Expression has something to do with the magic. It also raised the question of how does the lambda get automatically wrapped in an Expression object?
in MVC5 , what does #model, #html and #using mean, why and when we usually use ( # ) and which word follow it ?
For example : #model MVC_Project2.Models.stufftable is written in the first of re.cshtml page
stufftable is a table which is belong to users to create new user and the following code is written in the same page to create two textbox with two labels two labels to show the login page :
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(u => u.stuffname)
#Html.TextBoxFor(u => u.stuffname)
</div>
<div>
#Html.LabelFor(u => u.stuffpass)
#Html.PasswordFor(u => u.stuffpass)
</div>
<input type="submit" />
}
in a .cshtml file, everything that goes in it is HTML. So it will get written out exactly as its written.
In other words, if you just typed
model blah
without the # then when you render the view, it will actually display the words model blah on the page.
The # sign is a directive to tell the Razor engine that what follows is code, and it should compile that rather than simply write it to the output.
so when you type
#model blah
This is compiled by razor, and tells the Razor engine that the type of the model is 'blah', so that when you use the keyword Model (note the capital M and you would have to use the # sign as well) it will refer to the model you have defined (in this case blah).
So if you write
#model blah
#Model.Foo
then, if blah.Foo contained the number 14, it would write the number 14 to the output. As you might have surmised, the # symbol has many uses, so if you say #Model.Foo you're actually doing something like Response.Write(Model.Foo).
In general, the # symbol is used to transition from HTML mode, to code mode, in the same way the old ASPX code nuggets were used <% ... %>, however razor is a little smarter and understands the context of your code so it can infer where your code ends most of the time, so there is no need to have an ending bracket like in the old days.
#using is just like in C# code, it is the using statement that disposes of disposable resources after the block has ended. Razor uses this technique in many cases to signify the end of a block of code. So, for instance saying:
#using(Html.BeginForm()) {
....
}
The Html.BeginForm helper returns an object that defines an IDisposable interface, that gets called when the using statement ends, so BeginForm() in this case outputs a <form> tag, and when the IDisposable.Dispose() method is called at the end of the using statement, it outputs </form>. It's a technique that's used to wrap other code that outputs tags so that it can properly close their html.
#Html is also just C#. However, it's calling the HtmlHelper object (Razor defines an object called Html in the "ViewPage" class that backs the view, this Html object is of type HtmlHelper) and it calls various C# extension methods which have been defined on the HtmlHelper object. If you don't know what a C# Extension Method is, it's a way to extend objects without those objects having to be rewritten, this is more advanced C#. Suffice it to say, that something like #Html.TextBox() calls a method of type HtmlHelper.TextBox(), so it's just a C# method you can call, but these methods are created specifically as helpers to help you create your HTML.
There is a lot to this really, and if you don't understand the concepts I've discussed, then you really need to learn more about C# and/or HTML, as you are likely getting in over your head.
Clean and Simple: # is Razor Syntax. It helps you to insert C# code into your views (HTML code).
For Example:
#DateTime.Now
Will show you current date and time.
The # is used for directives in Razor code. #model, for example, binds the View to the model. # is also used to execute and print out back-end C# code in HTML. When you use #Html it calls a helper class that is part of the Mvc framework which returns an MvcHtmlString.
I’ve got a question about the default account model, view and controller generated when creating a new MVC 3 project in Visual Studio 2010 (using razor).
The generated AccountController uses this to load the view:
public ActionResult LogOn()
{
return View();
}
And the corresponding view (LogOn.cshtml) contains code like this:
#Html.LabelFor(m => m.UserName)
My question is where is this variable “m” defined? How does it know that this refers to the model? There is no model being passed to the view but "m" still works. If I change all the references to “m” to another letter it still works! Could someone explain what’s going on here?
Thanks
This is a C# 3.0 feature called "Lambda Expression".
You can check these nice articles to know what it is (by the way, it's amazingly useful).
http://blogs.msdn.com/b/ericwhite/archive/2006/10/03/lambda-expressions.aspx
http://blah.winsmarts.com/2006/05/19/demystifying-c-30--part-4-lambda-expressions.aspx
For the 2nd part of your question, if you notice, all the methods under #Html are model-related methods, which mean that all of them are expecting to work on your passed model.
And if you check the first line in your Logon view, you will find this line:
#model YOUR_APP_NAME.Models.LogOnModel
Which defines that the model type of this view is of type logonModel. (Which can be found inside your Models folder.)
This way, the weird m is represening the passed Logon model, and so we can access the properties under the passed model easily like typing m.UserName
The 'm' in this situation if a variable name that is supplied as part of a lamda expression.
From the link:
All lambda expressions use the lambda
operator =>, which is read as "goes
to". The left side of the lambda
operator specifies the input
parameters (if any) and the right side
holds the expression or statement
block. The lambda expression x => x *
x is read "x goes to x times x."
Lambda expressions are just shorthand C# delegates. Delegates are functions that can be passed as parameters, much like javascript functions, like callbacks.
x => x.Name is really just shorthand for creating one of these delegates, that takes some variable x as a parameter, and returns this variables Name property.
(parameters) => (expression)
Is shorthand for
Function(parameters) {
return expression;
}
So LabelFor takes one of these shorthand functions as parameters, and runs it against the model context you have specified.
What is the difference between mvc HTML.Control and ControlFor (TextBox, checkbox etc)..
One is strongly typed. If you have a view that expects a model of type Customer with a property "CustomerName", you can render the value with either way
<%=Html.Label("CustomerName") %>
<%=Html.LabelFor(a => a.CustomerName) %> //strongly typed
With the second method (lambda expression), you avoid magic strings. You also have the ability to inspect ModelMetadata to perform additional customizations.
Read about Model metadata here:
http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-2-modelmetadata.html
The For versions of the HTML helper methods take properties as strongly-typed lambda expressions instead of strings.
For example, the following to statements are equivalent:
<%=Html.TextBox("Description") $>
<%=Html.TextBoxFor(m => m.Description) $>
However, if you rename the Description property, the TextBoxFor call will give a compiler error, whereas the TextBox call will not fail until you visit that page.
The following article explains the difference in general:
http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx
Simply put, HTML.ControlFor is strongly typed, which allows use of lambda expressions and automatically takes the nameof the property specified as the name/id of the control.