MVC #model meaning - asp.net-mvc

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.

Related

Asp.Net MVC : difference between model and Model in Views

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.

Is there any way to create a custom MVC Razor element like "text"?

I want to create a custom razor tag like <text></text> to decide what to do with the html code inside of it. Is there any way to create razor elements like <text></text> element and add it to the razor engine?
I don't want to create any HtmlHelpers for this.
For Examle:
<WYSYWIG>
Hello There!
</WYSYWIG>
or
<WeatherChart City="NY">
</WeatherChart>
Explanation:
Well the idea is to have server tags to be translated (Parsed) to html codes by the attributes given to them. This kind of codes helps junior developers not to be involved with the complexity of controls.
The closest thing to what you are describing is to create display or editor templates. You can then define a template for a model and use it with #Html.DisplayFor() in the view.
Here is a good blog post to get you started aspnet mvc display and editor templates and a quick overview of the structure below.
Example
Model - WeatherChartModel.cs
public class WeatherChartModel
{
}
Display template - WeatherChart.cshtml
<div class="weather-chart">
// Some other stuff here
</div>
View - Index.cshtml
#model WeatherChartModel
#Html.DisplayForModel() // This will output the template view for the model
In order to create custom element handling in razor, such as <text>, you'd need to implement a custom System.Web.Razor.dll (which is responsible for parsing the document). Specifically, the class you're looking to re-implement would be the System.Web.Razor.Parser.HtmlMarkupParser.
However, I don't believe this is necessary given how flexible the framework itself is. If you're looking to keep things modular, have a look at either using DisplayTemplates/EditorTemplates or consider writing your own extension method. For example, either of the following would be more ideal:
#* TextField is decorated with UIHint("WYSIWYG"), therefore
calling ~/Views/Shared/EditorTemplates/WYSIWYG.cshtml *#
#Html.EditorFor(x => x.TextField)
#* WeatherField is decorated with UIHint("WeatherChart"), therefore
calling ~/Views/Shared/DisplayTemplates/WeatherChart.cshtml *#
#Html.DisplayFor(x => x.WeatherField)
Alternatively:
#* Custom extension method *#
#Html.WysiwygFor(x => x.TextField)
#* Another custom extension method *#
#Html.WeatherChartFor(x => x.WeatherField)

In an Editor Template call another Editor Template with the same Model

I have an editor template and within that editor template i want to call another editor template with the same model (i.e. nested), but it does not seem to display.
ie. \EditorTemplates\Template1.cshtml
#model foo
// insert code here to edit the default fields.
// display extra fields via another editor template.
#Html.EditorForModel("Template2") // or #Html.EditorFor(m => m, "Template2")
and \EditorTemplates\Template2.cshtml
#model foo
#Html.TextBoxFor(m => m.Name)
I am sure someone will question why? Well, the nested template will only be displayed if a condition is met (ie. #if (#Model.IsConditionMet) { .... } ), but I have left that out of my prototype for simplicity.
Short answer:
Use Html.Partial instead.
So, in your Template1.cshtml file:
#model foo
// insert code here to edit the default fields.
// display extra fields via another editor template.
#Html.Partial("EditorTemplates/Template2", Model)
Long answer:
This sadly appears to be by-design. MVC tracks the models that have been rendered, and if your model has already been rendered by a template, it won't do it twice, even if the template is different. Hence why the second #Html.EditorForModel("Template2") just does nothing.
Specifically, it's tracked in ViewData.TemplateInfo.VisitedObjects, which is an internal field, so there's no hope in you modifying it after the fact. The intention of this field is to prevent infinite recursion. Noble, but annoying in that it doesn't take the template used into account.
I found this out by looking at the source code, which is great for finding these weird idiosyncrasies of MVC.

ASP.NET MVC 3 - Partial vs Display Template vs Editor Template

So, the title should speak for itself.
To create re-usable components in ASP.NET MVC, we have 3 options (could be others i haven't mentioned):
Partial View:
#Html.Partial(Model.Foo, "SomePartial")
Custom Editor Template:
#Html.EditorFor(model => model.Foo)
Custom Display Template:
#Html.DisplayFor(model => model.Foo)
In terms of the actual View/HTML, all three implementations are identical:
#model WebApplications.Models.FooObject
<!-- Bunch of HTML -->
So, my question is - when/how do you decide which one of the three to use?
What i'm really looking for is a list of questions to ask yourself before creating one, for which the answers can be used to decide on which template to use.
Here's the 2 things i have found better with EditorFor/DisplayFor:
They respect model hierarchies when rendering HTML helpers (e.g if you have a "Bar" object on your "Foo" model, the HTML elements for "Bar" will be rendered with "Foo.Bar.ElementName", whilst a partial will have "ElementName").
More robust, e.g if you had a List<T> of something in your ViewModel, you could use #Html.DisplayFor(model => model.CollectionOfFoo), and MVC is smart enough to see it's a collection and render out the single display for each item (as opposed to a Partial, which would require an explicit for loop).
I've also heard DisplayFor renders a "read-only" template, but i don't understand that - couldn't i throw a form on there?
Can someone tell me some other reasons? Is there a list/article somewhere comparing the three?
EditorFor vs DisplayFor is simple. The semantics of the methods is to generate edit/insert and display/read only views (respectively). Use DisplayFor when displaying data (i.e. when you generate divs and spans that contain the model values). Use EditorFor when editing/inserting data (i.e. when you generate input tags inside a form).
The above methods are model-centric. This means that they will take the model metadata into account (for example you could annotate your model class with [UIHintAttribute] or [DisplayAttribute] and this would influence which template gets chosen to generate the UI for the model. They are also usually used for data models (i.e. models that represent rows in a database, etc)
On the other hand Partial is view-centric in that you are mostly concerned with choosing the correct partial view. The view doesn't necessarily need a model to function correctly. It can just have a common set of markup that gets reused throughout the site. Of course often times you want to affect the behavior of this partial in which case you might want to pass in an appropriate view model.
You did not ask about #Html.Action which also deserves a mention here. You could think of it as a more powerful version of Partial in that it executes a controller child action and then renders a view (which is usually a partial view). This is important because the child action can execute additional business logic that does not belong in a partial view. For example it could represent a shopping cart component. The reason to use it is to avoid performing the shopping cart-related work in every controller in your application.
Ultimately the choice depends on what is it that you are modelling in your application. Also remember that you can mix and match. For example you could have a partial view that calls the EditorFor helper. It really depends on what your application is and how to factor it to encourage maximum code reuse while avoiding repetition.
You certainly could customize DisplayFor to display an editable form. But the convention is for DisplayFor to be readonly and EditorFor to be for editing. Sticking with the convention will ensure that no matter what you pass into DisplayFor, it will do the same type of thing.
Just to give my 2c worth, our project is using a partial view with several jQuery tabs, and each tab rendering its fields with its own partial view. This worked fine until we added a feature whereby some of the tabs shared some common fields. Our first approach to this was to create another partial view with these common fields, but this got very clunky when using EditorFor and DropDownListFor to render fields and drop downs. In order to get the ids and names unique we had to render the fields with a prefix depending on the parent partial view that was rendering it:
<div id="div-#(idPrefix)2" class="toHide-#(idPrefix)" style="display:none">
<fieldset>
<label for="#(idPrefix).Frequency">Frequency<span style="color: #660000;"> *</span></label>
<input name="#(idPrefix).Frequency"
id="#(idPrefix)_Frequency"
style="width: 50%;"
type="text"
value="#(defaultTimePoint.Frequency)"
data-bind="value: viewState.#(viewStatePrefix).RecurringTimepoints.Frequency"
data-val="true"
data-val-required="The Frequency field is required."
data-val-number="The field Frequency must be a number."
data-val-range-min="1"
data-val-range-max="24"
data-val-range="The field Frequency must be between 1 and 24."
data-val-ignore="true"/>
#Html.ValidationMessage(idPrefix + ".Frequency")
... etc
</fieldset>
</div>
This got pretty ugly so we decided to use Editor Templates instead, which worked out much cleaner. We added a new View Model with the common fields, added a matching Editor Template, and rendered the fields using the Editor Template from different parent views. The Editor Template correctly renders the ids and names.
So in short, a compelling reason for us to use Editor Templates was the need to render some common fields in multiple tabs. Partial views aren't designed for this but Editor Templates handle the scenario perfectly.
Use _partial view approach if:
View Centric Logic
What to keep all _partial view related HTML in this view only. In the template method, you will have to keep some HTML outside the Template View like "Main Header or any outer border/settings.
Want to render partial view with logic (From controller) using URL.Action("action","controller").
Reasons to use Template:
Want to remove ForEach(Iterator). Template is well enough to identify Model as a list type. It will do it automatically.
Model Centric Logic. If multiple views are found in the same displayfor Template folder, then rendering will depend on Passed Model.
Another difference that hasn't been mentioned so far is that a partialview doesn't add model prefixes while a template does
Here is the issue

RenderAction RenderPartial

From what I have understood there is a big difference between the Html.RenderPartial included in the ASP.NET MVC release and the HTML.RenderAction in the Microsoft.Web.Mvc.ViewExtensions included in MVC Futures.
On my application I have many pages composed from many "widgets" (sort of) each having its own specific function.
It seemed to me more reasonable to use the RenderAction method as each widget would have a dedicated controller responsible for getting different data and rendering a dedicated view (as opposed to having only one controller and a unique view model to pass to RenderPartial helper to render views).
From the tests I have done having a form that points to a Create action method in a controller like:
<% using (Html.BeginForm("Create", "Message", FormMethod.Post,
new { id = "messageCreateForm" })) {%>
and calling it with
<% Html.RenderPartial("MessageForm",new MessageDTO()); %>
will render correcly a:
<form id="messageCreateForm" method="post" action="/Message/Create">
but with the same equivalent with RenderAction (so using a MessageForm action method on the controller to render the view) would not render correcly so:
<% Html.RenderAction<MessageController>(m => m.MessageForm()); %>
will render in:
<form id="messageCreateForm" method="post" action="">
Note that the action is empty.
Is this the correct way to use the RenderAction helper and is it correct to use it in cases like that?
UPDATE:
Actually renaming the partial view to _MessageForm renders the form correcly.
Very old one, but it jumped into my list of unanswered questions :)
There is a big difference between RenderAction and RenderPartial. RenderPartial will render a View on the same controller (or a shared one), while RenderAction will actually perform an entire cycle of MVC, that is: it will instantiate the controller (any controller you mention, not just the current one), it will execute the action, and it will then return and render the result.
The RenderPartial is more similar to an inclusion, it will even share the same model if you don't specify a different one.
The RenderAction is much more complex (and there may be undesired side effects, that's why they did not make this function available since version 1 -- initially it was available as an experimental feature).
So in your case, if you have widgets, it's OK to use both. It depends on the complexity of the widget. If you have one that has to get data from a DB, do something complex, etc... then you should probably use RenderAction.
I have a News controller responsible for news objects. I created a Block action, which will render a block with the latest news to be put in the home page. This is a perfect example, in my opinion, for RenderAction.
Working with MVC requires much attention to not to shoot yourself in the foot. I mean it by the efficiency of the MVC products. In complex projects I would prefer to use RenderPartial rather than RenderAction. I use RenderPartial in which I use jQuery.ajax request (with Html.Action). It definitely works more efficiently than RenderAction. By this way you can put your Views into cache and then call jQuery.ajax. Try it yourselves.
Ayende explains it clearly in Hibernating Rhinos.

Resources