Overwriting the class on a `Html.EditorFor` - asp.net-mvc-2

by the default with
<%: Html.EditorFor(m => m.ConfirmationHeadline) %>
the output is:
<input type="text" value=""
name="ConfirmationHeadline" id="ConfirmationHeadline"
class="text-box single-line">
As you can see, the input appends already a class attribute. Well, this should not be a problem, just use
<%: Html.EditorFor(m => m.ConfirmationHeadline, new { #class="span-11 last"}) %>
and should work... err... nope!
this will output the exact same code!
though, works fine with Html.TextAreaFor()
How can I remove the class text-box single-line from ever appear so my own classes could be appended? any T4 template I should edited?
Thank you for all the help.

There is no way to customize the value of the emitted class attribute when using built-in editor templates via the EditorFor method. It hard-codes the class value (more info available here: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html)
You have two options:
Write your own custom template that supports the extra functionality. Have a look here for more details: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html
Process the output of the EditorFor method:
<%: new HtmlString(Html.EditorFor(m=>m.ConfirmationHeadline).ToString()
.Replace("class=\"text-box single-line\"",
"class=\"text-box single-line span-11 last\"")) %>

In MCV 5.1 you can take advantage of htmlAttributes. Works like a charm...
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter your Name" } })

asp.net mvc creates a file called site.css in the content folder. There you can see that the text-box class is set to a width of 30em by default. Reset it to something saner like 15em. The single-line class doesn't appear to be defined anywhere.

You can use TextBoxFor instead

I had this same problem and didn't like any of the solutions above. I also found a similar post here, but I didn't like those solutions either. After some tooling around, I found something I liked, which let me continue to use the Editor Templates (which is something you should try to take advantage of whenever you can). I posted the solution here

try this code
#Html.Raw(
Html.EditorFor(m => m.DataInicial).ToString()
.Replace(
"\"text-box single-line\"",
"\"form-control text-box single-line\""))

Related

Zend Frameword 2: How to set a html link (img) in a legend of the fieldset?

I used zf2 to design a website.
And the form is something like this:
$this->add(array
'options'=>array(
'label'=> 'title1'))
And finally it shows like this:
<form>
<fieldset>
<legend>title1</legend>
<label>****</label>
</fielset>
</form>
Now, I wanna add a link or an image after the title1, for example:
<form>
<fieldset>
<legend>title1<a href=''>link</a></legend>
<label>****</label>
</fielset>
</form>
How can I do this?
You can't. Well, at least not without overwriting the specific ViewHelper (probably formCollection()). In ZF2 all Labels are run through the Zend\View\Helper\EscapeHtml ViewHelper. Therefore using any sort of HTML inside Labels is not supported in any way.
While going by specification it may be allowed to use inline-elements inside the <legend> Element, semantically it looks a little different. The <legend> shall do nothing but to describe the contents of the <fieldset>.
Anyways, opinions aside, as i've mentioned, you'll have to overwrite the ViewHelper and then skip the use of the EscapeHtml ViewHelper, as it's done in this line of the formCollection() Code

MVC3 and Razor - How to place a dynamic value for hidden field?

I'm a beginner about Razor, and sometimes I get stuck with really simple things.
I have this foreach loop:
#foreach (dynamic item in ViewBag.EAList)
{
<li>
#using (#Html.BeginForm("Duplicate, "Daily"))
{
<p>#item.AuthorComment</p>
#Html.Hidden("EstadoDeAlmaID", #item.EAID)
#Html.Hidden("PosterID", Session["id"].ToString())
<input type="submit" value="Send" />
}
</li>
}
This line:
#Html.Hidden("EstadoDeAlmaID", #item.EAID)
Doesn't work, and I don't know how to make it work, I tried many ways, without #, with (--), with #(--)...
Could someone help me to display the dynamic value in my hidden field?
In addition, if someone know about a good Razor samples websites, I would be very thankful.
I had the same problem, found that a simple cast solved my problem.
#Html.Hidden("id", (string) ViewBag.ebook.isbn)
In Razor, once you are in "C# land", you no longer need to prefix values with # sign.
This should suffice:
#Html.Hidden("EstadoDeAlmaID", item.EAID)
Check out Scott Gu's article covering the syntax for more help.
Update
And I would also move your <li></li> within your using block, as Razor works better when you wrap HTML blocks inside of a code blocks.
Also, your Html.BeginForm should live outside of your loop.
#using (#Html.BeginForm("Duplicate, "Daily"))
{
<ul>
#foreach (? item in ViewBag.EAList)
{
<li>
<p>#item.AuthorComment</p>
#Html.Hidden("EstadoDeAlmaID", item.EAID)
#Html.Hidden("PosterID", Session["id"].ToString())
<input type="submit" value="Send" />
</li>
}
</ul>
}
Where ? in the foreach loop is the type of your items in EAList.
To avoid the Extension methods cannot be dynamically dispatched exception, use a model instead of ViewBag so you will not be using dynamic objects (this will avoid all the unnecessary casting in the View and is more in line with MVC style in general):
In your action when you return the view:
return View("ViewName", db.EAList.ToList());
In your view, the first line should be:
#model IEnumerable<EAListItem> //or whatever the type name is
Then just do:
#foreach(var item in Model)
You got the error, "Extension methods cannot be dynamically dispatched"... therein lies your trouble.
You should declare you loop variable not to be of type dynamic, but of the actual type in the collection. Then remove the # from the item.EAID call inside the #Html.Hidden() call.
The simple solution for me was to use ViewData instead of ViewBag. ViewBag is just a dynamic wrapper around ViewData anyway.
#Html.Hidden("ReportID", ViewData["ReportID"])
but I don't know if this will help in your case or not since you are creating dynamic items in your foreach loop.
I have found that when i want to use the view bag data in the HTML
Getting back to basics has often worked for me
<input type="hidden" name="Data" id="Data" value="#ViewBag.Data" />
this gave the same result.

ASP.NET MVC 2 and lists as Hidden values?

Hi,
I have a View class that contains a list, this list explains the available files that the user have uploaded (rendered with an html helper).
To maintain this data on submit I have added the following to the view :
<%: Html.HiddenFor(model => model.ModelView.Files)%>
I was hoping that the mode.ModelView.Files list would be returned to the action on submit but it is not?
Is it not possible to have a list as hiddenfield?
More information : The user submit a couple of files that is saved on the service, when saved thay are refered to as GUID and is this list that is sent back to the user to render the saved images. The user makes some changes in the form and hit submit again the image list will be empty when getting to the control action, why?
BestRegards
Is it not possible to have a list as hiddenfield?
Of course that it is not possible. A hidden field takes only a single string value:
<input type="hidden" id="foo" name="foo" value="foo bar" />
So if you need a list you need multiple hidden fields, for each item of the list. And if those items are complex objects you need a hidden field for each property of each item of the list.
Or a much simpler solution is for this hidden field to represent some unique identifier:
<input type="hidden" id="filesId" name="filesId" value="123" />
and in your controller action you would use this unique identifier to refetch your collection from wherever you initially got it.
Yet another possibility is to persist your model into the Session (just mentioning the Session for the completeness of my answer sake, but it's not something that I would actually recommend using).
Before I start I'd just like to mention that this is an example of one of the proposed solutions that was marked as the answer. Darrin got it right, here's an example of an implementation of the suggested solution...
I had a similar problem where I needed to store a generic list of type int in a hiddenfield. I tried the standard apporach which would be:
<%: Html.HiddenFor(foo => foo.ListOfIntegers) %>
That would however cause and exception. So I tried Darrin's suggestion and replaced the code above with this:
<%
foreach(int fooInt in Model.ListOfIntegers)
{ %>
<%: Html.Hidden("ListOfIntegers", fooInt) %>
<% } %>
This worked like a charm for me. Thanks Darrin.

Asp.net Mvc Display template of String, but now every simple type wants to use it!

I created a Display Template which when passed a string renders a disabled text box
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<String>" %>
<%: Html.TextBoxFor(model => model, new { disabled = "disabled" })%>
Which works great. However, for some reason MVC wants to try and stuff DateTimes and Ints through it as well, which is throwing exceptions
The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'System.String'.
Any ideas?
You don't need to strongly type the template to a String.
you can try something like this :
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%= Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue,
, new { disabled = "disabled" }) %>
And in your view you call it like this
Html.DisplayModelFor(model => mode.name);
For more information see an example of the default built-in editor template for the string in Brad Wilson article in his his series on Templates in ASP.NET MVC.
You should consider going through the complete series. I can't express how helpful this series was for me.

MVC2 Custom HTML Helper and <%: %> Syntax

Is there any way to use a custom html helper with the <%: %> syntax ?
I know that if i'm use the code below, it's ok, but it's seems not so elegant and secure.
<%= Html.MyHelper("Some Data")%>
I mean, use <%= %> is the best practices?
Have your helper return an MvcHtmlString instead of a string. Also, please use <%: as much as possible.
HTML helpers create HTML, which is normally expected to be output raw with <%= %>. If you used <%: %> to HTML-escape the output of an HTML helper, you'll see the HTML source it produced on the page as text (eg literally <input name="foo" value="bar"> on-screen), which is probably not what you want.
It is up to the helper to HTML-escape any text content inside them, for safety. Yes, if you write a custom HTML helper and get it wrong—forgetting to HTML-encode strings your helper is putting in text content or attribute values in the output—you'll have security holes. You need to know what you're doing with escaping to write an HTML helper.
Microsoft, unfortunately, apparently don't, as the very first example in their tutorial completely fails:
return String.Format("<label for='{0}'>{1}</label>", target, text);
Whoops. Hope those ID and text strings didn't come from untrusted data!
[why are web tutorials always so lamentably terrible at escaping issues?]