mvc3 is there a way to change the naming system of razor - asp.net-mvc-3

I have a partial view that allows Html and the rendered name attribute of the <textarea> is throwing everything off, for instance this is my text area
#Html.TextAreaFor(model => model.cars.mycars)
causes the attribute to render as name="cars.mycars", is there anyway to change that to cars_mycars without using #Name ?
The reason why I want cars_mycars is because it is a field that has AllowHtml in it in the model
[AllowHtml]
public string mycars { get; set; }
In order for AllowHtml to work I would need a strongly typed model such as #Html.TextAreaFor(model => model.mycars) but I am using multiple models in 1 view therefore I have
#Html.TextAreaFor(model => model.cars.mycars, #new{id="cars_mycars",#Name="cars_mycars"})
This is all in a partialview and when I try to submit it nothing happens at all. That is the only field in the form so the issue much lie there and in addition if I put
ValidateInput(False)
on the action method then everything works fine which leads me back to the #name convention not working .

You can try like this
#Html.TextArea("cars_mycars")

Related

EditorTemplate for "Floats" not being called in ASP.NET MVC 3

I have a property of type "float" in my ViewModel. It's being displayed as a TextBox with a default value of "0".
I added an "EditorTemplates" folder inside the "Shared" folder & created a new "Float.cshtml" file with the following content:
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue == 0 ? "" : ViewData.TemplateInfo.FormattedModelValue, new { #class = "text-box single-line" })
However, still when I run the application, float fields are still being displayed with a default value of 0.
Thanks
UPDATE
I am just trying to see how ASP.NET reacts to custom templates, till now, the engine is not processing my custom template, something similar to:
LatLng.cshtml
#model float
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { #class = "text-box single-line "}) Latitude
On the ViewModel,
[UIHint("LatLng")]
public float? Latitude { get; set; }
On the View,
#Html.EditorFor(model => model.Latitude)
Nothing is changing, default template is being used.
Float is not actually a .NET type, it's a C# type. Float maps to System.Single, so you need to create a Single.cshtml and not a Float.cshtml.
You can also get around this by specifying a UIHint attribute on the model data, or by specifying the template to use in your Editor or EditorFor methods.
An easy workaround is if you just set ViewData.TemplateInfo.FormattedModelValue to return a string in the model, so you don't have to do that weird logic on the view. If you need it to post back a new value (for editing purposes), you just have to add some logic in the controller to turn the string back into a float.

ModelState validation errors for properties that are not present in my view

Suppose this view :
#Html.HiddenFor(model => model.Batiment.Client.Id)
#Html.LabelFor(model => model.Batiment.Code)</td>
#Html.EditorFor(model => model.Batiment.Code)</td>
<br>
#Html.LabelFor(model => model.Batiment.Nom)</td>
#Html.EditorFor(model => model.Batiment.Nom)</td>
When I submit my form on the controler the ModelState is invalid for the property "Nom" required into my class Client. Is true, the metadata in my class Client is set to required but I dont include this field into my view...! Why Mvc raise this error?
Can I hide a field (like Id) without specify all the required field into my view?
Errors enter model state during binding, therefore you could exclude your property from binding by including the following in your action method signature:
public ActionResult Register([Bind(Exclude="PropertyName")] UserViewModel user)
{
// Your logic here
}
This should exclude PropertyName from binding, therefore error won't enter your model state and your validation should succeed. Just to add, I think that this is more of a hack, rathern then solution. If you need only a part of your view model, than this view model should not be used and you should really consider creating a new view model without this property.
It might look very similar and it might seem like duplicate code, but it isn't. It promotes seperation of concerns and you should see the benefit of doing this in the near future when it comes to extending/modifying your application.
No, the validation is done on the model, not the view, why it is called 'model state'
You need to create another view for this scenario. This is exactly what ViewModels are for.
Then you can use a tool like AutoMapper to easily to copy the properties between this view model to your base model.

MVC 3 - Change Html.TextBox to Html.TextBoxFor

I am using html.textbox for 2 of my datetime field because I need to format them in a specific format but i don't know how to do it by html.textboxfor.
However, I realise i need to have the textboxfor for the validation in my model class to work:
[Required(ErrorMessage = "Storage Date is required")]
[DataType(DataType.DateTime, ErrorMessage = "Please input a valid date")]
public DateTime StorageDate { get; set; }
Any idea how can I change my Html.Textbox below into Html.TextBoxFor with the same setting??
#Html.TextBox("expirydate", String.Format("{0:ddd, d MMM yyyy}", DateTime.Now), new { id = "expirydate" })
#Html.ValidationMessageFor(model => model.ExpiryDate)
Appreciate any help... Thanks...
You don't really need to use TextBoxFor() for validation to work. If your TextBox has the same id as a field in the model, the model binder will pick it up. If you're talking about to get the unobtrusive validation features, you can always manually add the data-* attributes to your TextBox.
However, in this case it sounds like what you really want is a custom editor, using EditorFor(). It's a bit more work, but it will allow you to actually enforce the date/time formatting by giving the user something like a date/time picker control. The basic idea is:
Create a partial view called DateTime.cshtml that is bound to model of type Nullable<DateTime>, and put it into the Shared/EditorTemplates view folder.
Use jQuery and jQueryUI to put an HTML textbox that is styled as a date/time picker into the partial view.
Decorate the property on your model with the [DataType(DataType.DateTime)] attribute
Use Html.EditorFor(model => model.WhateverProperty)
Fortunately, date/time pickers are probably the most popular custom MVC3 editor, so there are plenty of examples to pick from; the code from this question works fine, just make sure to note the suggestion in the answer and replace this line in the partial view:
#inherits System.Web.Mvc.WebViewPage<System.DateTime>
with this:
#model System.DateTime?

Where does asp.net mvc text box input value is taken?

I have a url like this:
http://localhost/products/AddFeature?code=SMW
in the controller action, I create a model and set the
model.Code = "123112".
The View has this
#Html.EditorFor(model => model.Code)
the final rendered html always shows "SMW" as the value.
Is this a bug where the query string value overrides the assigned value ?
Does anyone got same results or I need some coffee ?
Clear the model state before returning your view. Be sure that you haven't missed some model error before you do that. The helpers use the ModelState, then the models for their values.
ModelState.Clear();

mvc 3 html attributes

i have been playing around with MVC. I am currently stumped on with html helper methods. One thing i have noticed is that I cant really cant apply the ASP.NET Web Form logic into MVC. To explain further, in ASP.NET I could create a Label control and assign it some text data and then read the text data.
However, in MVC, I cant seem to do the same with #Html.LabelFor/#Html.Label, I have realised that once you do a POST from your form, the value from the Label is not bound back into my view model. However, if I use an EditorFor or TextBoxFor, I can get values bound to my viewmodel upon POST.
My question what html hlper method should I use to display text as readonly but yet be able to bind back to my viewmodel upon post ? I have tried TextBoxFor with its html attributes set to disabled and readonly but no luck.
Appreciate any pointers.
thanks
You should be able to bind the readonly attribute to the TextBox by passing in htmlAttributes as the 2nd parameter of the TextBoxFor method:
<%=Html.TextBoxFor(m => m.SomeProperty, new { #readonly = "readonly" }) %>
On MSDN: InputExtensions.TextBoxFor Method (HtmlHelper, Expression>, Object)
If you're trying to maintain the Label value you can use a combination of the LabelFor and HiddenFor methods.
I don't know why you would need to do this though, since you should be able to get the DisplayText attribute or the Property Name from the property.
<%=Html.LabelFor(m => m.SomeProperty) %>
<%=Html.HiddenFor(m => m.SomeProperty) %>
but this doesn't make a lot of sense since the usual syntax would be:
<%=Html.LabelFor(m => m.SomeProperty) %>
<%=Html.TextBoxFor(m => m.SomeProperty) %>
Note that if you use the disabled attribute the input will not be posted when the form is submitted
This is expected behaviour, only values form elements are added to your Model on POST so your label will be ignored. To get around this duplicate your label value in a hidden field
Html.HiddenFor(model => model.FieldName)
or
Html.Hidden("FieldName", model.FieldName)

Resources