Asp.net mvc html.raw doesnt resolve - asp.net-mvc

#Html.Raw(HttpUtility.HtmlDecode(Model.Id.ToString()))
always return 0 in the Index.cshtml file placed under "EditorTemplates" folder
Am i doing anything incorrect
I have the model defined at the top of the page as
#model [Namespace].ViewModel

If the id is numeric, there is no reason to use Html.Raw at all. There is no HTML code in the value that should aviod the normal HTML encoding.
Just use:
#Model.Id
The value will implicitly be converted to a string, so the ToString call is not needed either.
If it doesn't show the expected value, you know that it wasn't there in the first place.

Related

Html.Textbox helper not setting the value of textbox in MVC5 Razor

I am using MVC5 ASP.Net with Razor Engine for a view that has following html helper for displaying a textbox and setting its value to ViewBag.SearchText.
When user inputs text into this textbox and view posts back, then the value is set correctly according to value in ViewBag.SearchText, but when in controller's action the ViewBag.SearchText = string.Empty, then textbox still retains its original value rather than an empty string.
Is this how the Html helper for textbox is supposed to behave Or I am missing something, and how could I set the value of textbox to an empty string? This is quite strange since the ViewBag.SearchText value is an empty string when I step through code in Visual Studio 2013.
#Html.TextBox("SearchText", (string)ViewBag.SearchText)
UPDATE 1:
I found that using the code Model.Clear() at start of the controller action solved this problem. However, I found another way to just clear that part of ModelState that is used to populate the textbox after postback. The key in ModelState is the id of the textbox, which is 'SearchText'.
The code for this is as below.
ModelState.SetModelValue("SearchText", new ValueProviderResult(null,string.Empty,
System.Globalization.CultureInfo.InvariantCulture));
That's by default (ModelState retains the value on post back).
You can use ModelState.Clear() before setting ViewBag.SearchText = ""; and returning the view. However use with caution because clearing ModelState can have unexpected results if your using validation

Html.DisplayFor and Html.EditorFor displays different values

I'm completely stumped.
I'm doing a searchform in MVC2 (I've done dozen others on this project, all working fine.)
Global.asax has this route:
routes.MapRoute("OnlineHelpSearchIndex",
"Help/Search/{expression}/{page}",
new { controller = "OnlineHelp", action = "Search", expression = UrlParameter.Optional, page=1 });
The expression is a base64 encoded string. I decode it in controller, pass it to a model which has a property named Expression, and display it in a PartialView in a TextBox. (Then when the user clicks a link or presses enter, I encode the string in javascript and send it to "/Help/Search/"+value)
I have several searchboxes built this way (each with a route SomeModule/Search/{expression}), and one of them is not working.
<%:Html.DisplayFor(m => m.Expression)%>
<%: Model.Expression %>
<%:Html.TextAreaFor(m => m.Expression)%>
<%:Html.TextBoxFor(m => m.Expression)%>
<%:Html.EditorFor(m => m.Expression)%>
The first two display the correct expression, the other three displays the expression in the url.
I tried hardcoding a string into the model, the first two displayed the hardcoded string, the other three displayed whatever was in the url. How is it possible?
(I even tried with JS disabled, so it is a server side issue)
I know this is an old thread, but I figured I would answer it anyway. The reason this is happening is intentional, it is due to ModelState. See this question for another case:
Asp.net MVC ModelState.Clear
Long story short, you're POSTing form data to a controller and returning a View, and using Helpers. Therefore, MVC assumes this is a failure on validation and is returning the ModelState value, not the value of your Model data. The first two are displaying correctly because they are not editors, the other 3 are editors, so they're showing ModelState.
Either call ModelState.Clear() in the controller to blow it away, or implement another design pattern, such as POST, Redirect, GET.
Try to change the name of the expression parameter in both the routes.MapRoute and in your OnlineHelp/Search controller/action method:
routes.MapRoute("OnlineHelpSearchIndex",
"Help/Search/{exprs}/{page}",
new { controller = "OnlineHelp", action = "Search", exprs = UrlParameter.Optional, page=1 });
(or, if you prefer, you can change the name of the Expression property of your model).
This often happens working with form fields created by HtmlHelper methods such as TextBoxFor/EditorFor, when the ViewModel has one or more properties that share the same name of a Router/Controller parameter: you can easily check this looking at the generated HTML code, your input-type fields created by the HtmlHelper methods will most likely have an id='Expression' attribute which causes the whole problem.

Html.RenderPartial giving me strange overload error?

I made a test partial page named _Test.cshtml and put it in the same directory as my view that will be calling it, here it is:
<div>hi</div>
And in the calling cshtml view, I simply put:
#Html.RenderPartial("_Test")
Which gives me the error:
CS1502: The best overloaded method
match for
'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)'
has some invalid arguments
I have also tried the full path with the same result.
I am very confused as to why this is acting this way, I assume I am missing something simple?
You are getting this error because Html.RenderXXX helpers return void - they have nothing to return because they are writing stuff directly* to response. You should use them like this:
#{ Html.RenderPartial("_Test"); }
There is also Html.Partial helper, which will work with your syntax, but I'd not recommend using it unless you have to, because of performance (it first composes given partial view into string, and then parent view puts it into response*).
* this is not entirely true, they are actually being rendered into ViewContext.Writer and once whole page is rendered and composed, the whole thing goes to response

Razor: #Html.Partial() vs #RenderPage()

What is the appropriate way of rendering a child template?
And what's the difference? Both seem to work for me.
And why does #Html.RenderPartial() no longer work?
Html.Partial("MyView")
Renders the "MyView" view to an MvcHtmlString. It follows the standard rules for view lookup (i.e. check current directory, then check the Shared directory).
Html.RenderPartial("MyView")
Does the same as Html.Partial(), except that it writes its output directly to the response stream. This is more efficient, because the view content is not buffered in memory. However, because the method does not return any output, #Html.RenderPartial("MyView") won't work. You have to wrap the call in a code block instead: #{Html.RenderPartial("MyView");}.
RenderPage("MyView.cshtml")
Renders the specified view (identified by path and file name rather than by view name) directly to the response stream, like Html.RenderPartial(). You can supply any model you like to the view by including it as a second parameter
RenderPage("MyView.cshtml", MyModel)
I prefer
#RenderPage("_LayoutHeader.cshtml")
Over
#{ Html.RenderPartial("_LayoutHeader"); }
Only because the syntax is easier and it is more readable. Other than that there doesn't seem to be any differences functionality wise.
EDIT: One advantage of RenderPartial is you don't have to specify the entire path or file extension it will search the common places automatically.
The RenderPartial method doesn’t return HTML markup like most other helper methods. Instead, it writes
content directly to the response stream, which is why we must call it like a complete line of C#, using a semicolon.
This is slightly more efficient than buffering the rendered HTML from the partial view, since it will be written to the
response stream anyway. If you prefer a more consistent syntax, you can use the Html.Partial method, which
does exactly the same as the RenderPartial method, but returns an HTML fragment and can be used as
#Html.Partial("Product", p).
We can also pass model using partial views. #Html.Partial("MyView","MyModel");
#RenderPages()
The above does not work in ASP.NET MVC. It only works in WebPages.
#Html.Partial("_Footer")
You will need to use the above in ASP.NET MVC.
For ASP.NET Core 7. In the Shared folder make partial file then user this following code
<partial name="_NavBar" />

ASP.NET MVC: Custom Html Helpers in Razor

I am having difficulty with Html Helpers when used with Razor. Said helpers worked fine in MVC 2 with the web form view engine. But not in razor. The error I get at runtime is:
Compiler Error Message: CS1502: The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments
Source Error:
Line 1: #using Wingspan.Web.Mvc;
Line 2: #Html.IncrementalMenu(MenuBlock.Site)
Expanding the Show Detailed Compiler Output reveals:
d:\...\Views\Shared\MenuTop.cshtml(2,1): error CS1502: The best overloaded method match for 'System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments
d:\...\Views\Shared\MenuTop.cshtml(2,7): error CS1503: Argument 1: cannot convert from 'void' to 'System.Web.WebPages.HelperResult'
That indicates to me that razor doesn't like my helper, IncrementalMenu, returning void (which works fine in MVC 2 web form engine views).
I get no errors at Compile time, although the line of code (#Html.IncrementalMenu(...)) is red underlined with the following message:
Cannot implicitly convert type 'void' to 'object'
IncrementalMenu is in the Wingspan.Web.Mvc namespace. It's signature is as follows:
public static void IncrementalMenu(this HtmlHelper html, MenuBlock menuBlock)
{
// Uses an HtmlTextWriter to render a menu from the sitemap
}
I'm blowed if I know what is wrong...
PS:
The MenuBlock parameter is just an enum that identifies how the menu should render. Don't fixate on this as that is fine.
You can call your helper like this:
#{ Html.IncrementalMenu(MenuBlock.Site); }
WebForms syntax
<% Html.IncrementalMenu(MenuBlock.Site); %>
You just call your method, and the return value (if there is any) is ignored.
Code like this expects a return value, and writes the return value to the html stream:
#Html.YourHelper()
Webforms syntax:
<%: Html.YourHelper() %>
The same, if result value != IHtmlString:
<%= Server.HtmlEncode(Html.YourHelper()) %>
Addendum:
You can get the same, or similar, error with #Html.RenderPartial. In this case it is due to the fact that RenderPartial renders directly to the Response, so is not a string and needs to be coded inside a "Razor code block":
#{
Html.RenderPartial(...);
}
I suspect that is one of the reasons that Microsoft have included in ASP.NET MVC the new Html.Partial. As Html.Partial does return a string, it is OK to write:
#Html.Partial
Which looks a lot better. Given that one of Razor's declared objectives is to be easy on the eye, this is quite likely true.
It also kind of makes me, at least, feel more comfortable. I know what returning a string is, I do it all the time. But "returning to the Response" requires a few more brain cycles every time I think it.
And it fits with the old adage that finally Microsoft get their products right in version 3. EG, Access 97.
Which is a depressing simile. Cos they screwed things up in version 4, ie, Access 2000...
Your HTML helper should return MvcHtmlString which represents the html in order to work properly with Razor (and other view engines that are not the WebFormsViewEngine)
public static MvcHtmlString Label(this HtmlHelper html, string expression)
{
return MvcHtmlString.Create("<label>" + expression + "</label>");
}

Resources