Questions about ASP.NET Razor - asp.net-mvc

I am reading a book about ASP.NET MVC using Razor syntax and got confused about some codes that in the book. Just wondering what does that mean
#using(Html.BeginForm("AddToCart", "Cart")) {....})
Why use "using" key word here? Can anyone explain to me a little bit, thx.

in this scenario, razor will generate following code in HTML
<form action="/Cart/AddToCart" method="post">
</form>
now with the "using" statement, there are two purpose:
to import the namespace
declare the variable in the using statement will call iDisposable method when it goes out from the close bracket.
In the above scenario it is just a indication of when to open the form tag and close tag.
ref: http://msdn.microsoft.com/en-us/library/yh598w02.aspx

When using this syntax, closing form tag is rendered at the end of using statement automatically.
You can check the documentation here
BeginForm Method

Manual http://msdn.microsoft.com/en-us/library/dd460542(v=vs.108).aspx
You can use this method in a using block. In that case, the method renders the closing tag at the end of the using block.

The using statement makes sure to call the Dispose method of an IDisposable interface.
public static MvcForm BeginForm(this HtmlHelper htmlHelper)
MvcForm implements IDisposable such that it calls EndForm internally. EndForm closes the form tag and injects any validation fields or required JavaScript.

Related

MVC #model meaning

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.

Razor - Inline helper with multiple tags

I can call a method which accepts an HTML/Razor block as a parameter like so:
#Html.SiteText(#<div>Some content</div>)
Calling the same method with multiple top level tags fails due to a parser error. I.E.
#Html.SiteText(#<div>Some content</div><div>Some more content</div>)
fails with:
Compiler Error Message: CS1026: ) expected
Is there any way to pass a Razor helper which has multiple top level tags?
Edit:
Here's the signature of the SiteText extension method:
public static IHtmlString SiteText(this HtmlHelper htmlHelper, Func<object, HelperResult> content)
The actual implementation of the method shouldn't matter, as this applies to how the method is invoked rather than what the implementation does with the inputs.
The simple way to look at it is that the Razor view engine is looking at each of those div tags as a single property.
Wrapping them in a text tag should resolve the issue:
#Html.SiteText(#<text><div>Some content</div><div>Some more content</div></text>)
Not tested but I suspect this will solve it:
#Html.SiteText(#<text>
<div>Some content</div>
<div>Some more content</div>
</text>)

Creating declarative MVC3 Razor Helper like Helper.BeginForm()

Creating MVC3 Razor Helper like Helper.BeginForm()
says that it can be done using extension methods and implementing IDisposable. Can the same be done by using declarative Razor helpers eg. #helper SomeHelper(){}?
Sort of.
Razor helpers return raw HTML, not IDisposable, so you can't use it with using.
However, you can create a Razor helper in App_Code to render the content, then call it from a normal extension method that writes the content directly to the page and returns a separate IDisposable.
No because helper.BeginForm() requires the IDisposable method to write out the closing </form> tag. As a razor helper is essentially a method and not a class it can't implement IDisposable.

How to alter the rendering of links in ASP.NET MVC?

Our designers have come up with button styles for an application which require the addition of <span> tags inside the <a> tags of our links.
In ASP.NET we implemented this by adding an App_Browsers entry for Link Buttons.
How would I go about doing this in ASP.NET MVC?
I've contemplated creating my own versions of all of the various HTML helper functions for creating ActionLinks and RouteLinks but this seems to be quite a 'brute force' way of doing things.
Is there a nice elegant way of doing it?
I know we could write some simple jQuery to do it, but we'd rather have the markup coming out of the server correctly in the first place.
Actually I think writing a new helper is exactly the way I would go. Seems to me that that's exactly what they are there for and it makes them very re-usable too.
You could always write one extension method, that takes another one (one of the built-in ones) as an argument, and wrappes the <span> around your link text before calling it. It should be quite easy to do with lambdas...
public static string SpanLink(this HtmlHelper helper,
string linkText, object args, Action<string> action)
where TController : IController
{
action("<span>" + linkText + "</span>", args);
}
And to call it:
<%= Html.SpanLink<HomeController>("link text", (s) => Html.ActionLink<HomeController>(c => c.Index(s));
(This code is typed directly into the answer field of SO - I haven't even checked it to make sure it compiles. So bear with me if it doesn't work on the first try...)

Rendering partial views with a model and htmlhelper

ASP .NET MVC 1
I'd like to show a partial view base on a model, and I'd like that to have a fairly short command for that. So I saw a way of using both a HtmlHelper and a controller (And I'd use another controller for that, not the controller currently used).
But somehow it still gives an error, though I think the method starts to look as it should.
So what am I doing wrong? (If I call the method directly in the ASPX-page, it succeeds. But it should be possible to use a HtmlHelper for that).
public static void RenderPartialView(this HtmlHelper html, string action, string controller, object model)
{
var context = html.ViewContext;
RouteData rd = new RouteData(context.RouteData.Route, context.RouteData.RouteHandler);
rd.Values.Add("controller", controller);
rd.Values.Add("action", action);
rd.Values.Add("model", model);
IHttpHandler handler = new MvcHandler(new RequestContext(context.HttpContext, rd));
handler.ProcessRequest(System.Web.HttpContext.Current);
}
Part in the ASCX-page:
<% Html.RenderPartialView("Show", "Intro", Model.Intro); %>
Error given:
'System.Web.Mvc.HtmlHelper' does not contain a definition for 'RenderPartialView' and no extension method 'RenderPartialView' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)
Why don't you use Html.RenderPartial ? It's the correct way to render a partial view. No need to make another request.
<% Html.RenderPartial("Show", Model.Intro); %>
Your call does not succeed beacause when you use an extension method in a "non static" way (i.e, as if the method belongs to an instance), you must omit the first parameter. The correct call would be
<% Html.RenderPartialView("Show", "Intro", Model.Intro); %>
Hope it helps
Cédric
Add
<add namespace="Namespace-Of-RenderPartialView-Class"/>
to your web.config file.
With extension methods, you don't need to include the first argument (the "this HtmlHelper html"). That is handled by the compiler when using extension methods. It is inferred based on the object you're calling the method on.

Resources