unobtrusive validation RANGE does not work - asp.net-mvc-3

I am doing an MVC 3 application. I have a model with [Range(1, 175, ErrorMessage="Invalid")].
On one of the controllers the view renders perfectly with all markup for validation. On a second Controller with the same setup the Range validation which is done on a dropdownlist, does not appear on the html markup. I have validation and unostrusiveValidation true on config.web. I am using LINQTOSQL and I have done a partial class to add the additional metadata. The field does pick up the [Display(Name="State")], but the Range is not.
<tr>
<td>#Html.LabelFor(x => x.carta.INVprovincia)</td>
<td>#Html.DropDownListFor(x => x.carta.INVprovincia, Model.provinciaItems, new { #class = "ddlsmall" }) <br /> #Html.ValidationMessageFor(x => x.carta.INVprovincia)</td>
</tr>
<tr>
<td>#Html.LabelFor(x => x.carta.INVmunicipio)</td>
<td>#Html.DropDownListFor(x => x.carta.INVmunicipio, Model.municipiosItems, new { #class = "ddlsmall" }) <br /> #Html.ValidationMessageFor(x => x.carta.INVmunicipio)</td>
</tr>

The Html.XXX helpers won't generate HTML5 data-* attributes used by the unobtrusive validation framework if they are not inside a form which seems to be your case. I guess that the form is contained within a parent view. This bug (IMHO) is fixed in ASP.NET MVC 4. A possible workaround is to put the following on the to of your partial view to fake a form and make the helpers believe that they are inside a form:
#{
ViewContext.FormContext = new FormContext();
}

Related

Html.BeginForm and Kendo Ui in MVC 4

So what I have is a form created with the beginform extension like this
using (Html.BeginForm("SendEmail", "Email", FormMethod.Post, new { id = "emailForm",
onsubmit = "return Check();"})){
inside I created some Kendo Ui widget like this
<table>
<tr>
<td>#Html.LabelFor(x => x.Senders)</td>
<td>
#(Html.Kendo().DropDownList()
.Name("Sender")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Model.Senders))
</td>
</tr>
<tr>
<td>#Html.Raw(Server.HtmlDecode(#Model.RecipientTable))</td>
</tr>
<tr>
<td colspan ="2">
#(Html.Kendo().MultiSelect()
.Name("Users")
.DataTextField("Name")
.DataValueField("Id")
.Placeholder("Optional - Choose additional users to send emails to:")
.ItemTemplate("#=LastName #, #=FirstName # #=MiddleInitial #")
.TagTemplate("#=LastName #, #=FirstName # #=MiddleInitial #")
.BindTo(Model.OptionalUsers))
</td>
</tr>
in my controller Email I have this method
[HttpPost]
public bool SendEmail(EmailModel Email){ .. stuff....}
Where the EmailModel is tightly bind to the view that contains the form from above. The question and trouble I am having is that is it possible and if so how, to have the model passed to the method containing information about what the user chose? Or is it that I can not use the form's submit and will have to manually get the value and pass it as a JSON to the controller via custom function that does a ajax call?
I thought I read that you weren't using post. The only items that are returned automatically through the post are fields that have been put in a for helper. What we do is
#Html.DropDownListFor(x => x.Sender, new { #class = "ddlSender" })
then in the script we initialize the kendo part of it
$('.ddlSender').kendoDropDownList();
this way the model item is put in a for helper so it gets posted back to the controller and you get the benefits of the kendo dropdown. Hope this helps

DropDownListFor loses list binding in validation

I am using fluentvalidation and mvc3. I have a drop down list, and it works well. I wanted to test my validation and it works EXCEPT that on validation the drop down list is empty??
What I mean is that if I purposely submit while the default SelectListItem Please Select...with a value of zero is chosen then the submit fails validation and the message shows etc. but my dropdownlist is now empty??
My controller code populating the list:
if (extforum.Count > 0)
{
foreach (var s in extforum)
model.ExternalSubscription.AvailableForums.Add(new SelectListItem(){ Text = s.ForumName, Value = s.Id.ToString() });
}
else
model.ExternalSubscription.AvailableForums.Add(new SelectListItem() { Text = "None Available", Value = "0" });
//add default value
model.ExternalSubscription.AvailableForums.Add(new SelectListItem() { Text="Please Select", Value="0", Selected=true });
My razor code:
<tr>
<td>
#Html.LabelFor(model => model.ForumName):
</td>
<td>
#Html.DropDownListFor(model => model.SelectedExtBoardId, Model.AvailableForums)
#Html.RequiredHint()
#Html.ValidationMessageFor(model => model.ExtForumBoardId)
</td>
</tr>
My validator code:
RuleFor(x => x.ExtForumBoardId)
.NotEqual(0).WithMessage("Blah"));
In your HttpPost controller action you must populate the AvailableForums collection property on your view model the same way you did in your Get action that rendered the form. This is necessary if you intend to redisplay the same view containing the dropdown. This often happens in the case of a validation error. Don't forget that when you submit a form, only the selected value of the dropdown is sent to the server. The collection of all possible values is something that you need to retrieve from your backend if you intend to redisplay the same view.

MV3 input validation - IE8 & IE9 behave differently

I'm using DataAnnotations to validate my input fields on a MVC3 application. I'm using regular expressions validations.
I get the validation messages on the UI for IE8 & IE9.
But I notice the difference when I hit the Save button even after the client side validation has failed.
IE9 keeps me on the client side.
On IE8 however, the control goes to the controller action, and I have to have a controller side TryValidateModel so that the validation errors out.
Does anyone know why IE8 is doing a server round trip?
Edit:
Adding the code. This goes into the cshtml.
#using (Html.BeginForm("Person", "Account", FormMethod.Post))
{
<span class="resultError" id="resultError">
#Html.ValidationMessageFor(model => model.Name, "Name should not contain special characters")
</span>
<table>
<tr>
<td class="editor-label">Name:
</td>
<td class="editor-field">#Html.EditorFor(model => model.Name)
</td>
</tr>
</table>
<input type="submit" name="btnKey" value="Save" />
}
This is the partial class using DataAnnotation. The Person class is driven by EF. So I have to create a metadata class to do the validation.
[MetadataType(typeof(personMetadata))]
public partial class person: EntityObject
{
public class personMetadata
{
[Required]
[RegularExpression(#"[A-Za-z0-9]+")]
public object Name { get; set; }
}
}
Edit: Adding the javascript files that are referenced.
"~/Scripts/jquery.validate.min.js"
"~/Scripts/jquery.validate.unobtrusive.min.js"
In my case, which is a lot like yours, I found that updating jquery.validate.js was the way to go. There is a reported bug on version 1.8.0 of jquery validation about IE 7, 8 and 9.
After getting the latest version everything started to work.

MVC 3 EditorTemplate - Model properties are empty

I have a number of custom EditorTemplates for various model classes. Inside these templates I obviously need to reference the properties of the model. My problem is that when I use the direct syntax of Model.Id (for example), the value is null. Another example is Model.Name which returns an empty string. However, when I reference the model in an expression (eg. #Html.TextBoxFor(i => i.Name)) then the values are there.
To further illustrate, here is a code snippet:
#model Vigilaris.Booking.Services.CompanyDTO
<div>
<fieldset class="editfieldset">
<legend class="titlelegend">Company Details</legend>
<ol>
<li>
#Html.TextBox("tb1", #Model.Id)
#Html.TextBox("tb2", #Model.Name)
</li>
<li>
#Html.LabelFor(i => i.CreatedDate)
#Html.DisplayFor(i => i.CreatedDate)
</li>
<li>
#Html.LabelFor(i => i.Name)
#Html.TextBoxFor(i => i.Name)
</li>
<li>
#Html.LabelFor(i => i.Description)
#Html.TextAreaFor(i => i.Description)
</li>
<li>
#Html.LabelFor(i => i.Phone)
#Html.TextBoxFor(i => i.Phone)
</li>
</ol>
</fieldset>
</div>
In this example, all the code that is using the LabelFor and DisplayFor helper functions displays the data from the model. However, the Html.TextBox code portion returns 0 for Model.Id and empty string for Name.
Why does it not access the actual model data when I reference Model directly?
I am unable to reproduce this. You might need to provide more context (controllers, views, ...). Also shouldn't your textbox be named like this:
#Html.TextBox("Id", Model.Id)
#Html.TextBox("Name", Model.Name)
and also why not using the strongly typed version directly:
#Html.TextBoxFor(x => x.Id)
#Html.TextBox(x => x.Name)
I managed to figure this one out. One thing I left out in my problem description was that I am using Telerik MVC Grid extension and the EditorTemplate is being using for In-form editing. So, the Model properties are not available at this point and this is understandable behaviour. I had to use a client side onEdit event on the Telerik MVC Grid and then set these values as necessary.
How I remember solving this is that I added a ClientEvent in my Telerik MVC Grid as follows:
.ClientEvents(events => events.OnEdit("Users_onEdit"))
This tells the grid to run my javascript function called Users_onEdit when an edit is triggered. Then, in my javascript function I find the field I want and then set its value. Here is an code excerpt:
function Users_onEdit(e) {
if (e.mode == "insert") {
$("#UserName").removeAttr("readonly");
$("#UserName").removeAttr("title");
$("#divNewUserMessage").show();
var formId = String(e.form.id);
var formIndex = formId.indexOf("form");
var companyId = formId.substr(6, formIndex -6);
var hiddenCompanyId = $(e.form).find("#CompanyId");
hiddenCompanyId.val(companyId);
}
}
I hope this helps others out there.

ASP.NET MVC 3 - Validation Question

Good evening everyone I have a question regarding validation of drop-down list values. I have a view that is bound to a view model type called ReservationData.
This object contains a property CustomerVehicles of type List<VehicleData>. VehicleData has two int properties VehicleMakeId and VehicleModelId.
On my view I am trying to loop over the number of items in the CustomerVehicles collection and displaying two dropdowns for each, a vehicle make dropdown and a vehicle model dropdown using DropDownListFor.
When I try to submit and validate I do not see any validation errors displayed on the screen.
Just in case you are wondering I have added a ValidationMessageFor for each dropdown as well. I am not sure if this is an issue with the structure of my view model and its complexity and how the controls need to be named or how the ids need to be set. Any help would be greatly appreciated.
Here is the code for the looping over the collection:
#for (var i = 0; i < Model.CustomerVehicles.Count(); i++)
{
var vehicleNumber = i + 1;
<div class="vehicle-selection-wrapper">
<div class="content-container">
<h3>
Vehicle #vehicleNumber</h3>
<img class="vehicle-image" alt="manufacturer image" src="#Url.Content("~/Content/images/default-vehicle.gif")" /><br />
#Html.LabelFor(m => m.CustomerVehicles[i].VehicleMakeId)
#Html.DropDownListFor(m => m.CustomerVehicles[i].VehicleMakeId
, new SelectList(Model.VehicleMakes, "Id", "Name")
, #UIDisplay.Dropdown_DefaultOption, new { #class = "long-field" })<br />
#Html.ValidationMessageFor(m => m.CustomerVehicles[i].VehicleMakeId)<br />
#Html.LabelFor(m => m.CustomerVehicles[i].VehicleModelId)
#Html.DropDownListFor(m => m.CustomerVehicles[i].VehicleModelId
, new SelectList(new List<CWR.Domain.VehicleModel>(), "Id", "Name")
, #UIDisplay.Dropdown_DefaultOption, new { #class = "long-field" })
#Html.ValidationMessageFor(m => m.CustomerVehicles[i].VehicleModelId)
</div>
</div>
}
Ok so I also noticed that in the generated HTML the selects that are generated are missing the HTML5 data-val attributes that are associated to elements to handle validation. Here is the generated HTML
<select class="long-field" id="CustomerVehicles_0__VehicleMakeId" name="CustomerVehicles[0].VehicleMakeId"><option value="">-- Select --</option>
</select><br />
<span class="field-validation-valid" data-valmsg- for="CustomerVehicles[0].VehicleMakeId" data-valmsg-replace="true"></span><br />
<label for="CustomerVehicles_0__VehicleModelId">Model</label>
<select class="long-field" id="CustomerVehicles_0__VehicleModelId" name="CustomerVehicles[0].VehicleModelId"><option value="">-- Select --</option>
</select>
<span class="field-validation-valid" data-valmsg-for="CustomerVehicles[0].VehicleModelId" data-valmsg-replace="true"></span>
Additionally in my VehicleData class the VehicleMakeId and VehicleModelId properties are decorated with a Required attribute.
UPDATE:
Ok so I was testing and noticed that if I keep my code identical except I swap the Html.DropdownListFor calls with Html.TextboxFor calls then the validation works. What could be causing this? Could it be a framework bug with the unobtrusive validation?
UPDATE: Contains Fix
So after posting this same question on the ASP.NET Forums, I was able to get a solution. In the post you will be able to see that there is a bug in the unobtrusive validation framework and how it handles validation of dropdownlists. The user counsellorben does a good job in explaining the problem as well as a solution (including sample code) that will assist others in avoiding this issue in the future, or at least until Microsoft builds in a fix in to the framework.
Thank you everyone for your assistance.
I too have come across this obviously massive oversight regarding client side validation with dropdownlists in MVC 3 and the best solution I can offer is to put the missing HMTL attributes in yourself.
In your view model create a property like this.
public Dictionary<string, object> CustomerVechicleAttributes
{
get
{
Dictionary<string, object> d = new Dictionary<string, object>();
d.Add("data-val", "true");
d.Add("data-val-required", "Please select a Vechicle.");
return d;
}
}
Then in your code, enter
#Html.DropDownListFor(m => m.CustomerVehicles[i].VehicleMakeId
, new SelectList(Model.VehicleMakes, "Id", "Name")
, #UIDisplay.Dropdown_DefaultOption,
**Model.CustomerVechicleAttributes** })
Just add the Model.CustomerVechicleAttributes as htmlAttributes to your dropdownlist.
This will inject the necessary attributes that are missing. You will of course need to add any other attributes you may need like your class attribute.
Hope this helps.
This is the simpliest way I found to do it, just adding data-val-*-* attributes in HtmlAttributes of DropDownListFor, inside the view. The following method works with RemoteValidation too, if you do not need remote validation, simply remove the elements containing data-val-remote-*:
#Html.DropDownListFor(m => m.yourlistID, (IEnumerable<SelectListItem>)ViewBag.YourListID, String.Empty,
new Dictionary<string, object>() { { "data-val", "true" },
{ "data-val-remote-url", "/Validation/yourremoteval" },
{ "data-val-remote-type", "POST" }, { "data-val-remote-additionalfield", "youradditionalfieldtovalidate" } })
I hope it may help. Best Regards!
you should try to add data annotations on your view model properties first so you could see the validation messages.
you might find what you need here
http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx
or create custom ones if needed.
what exactly do you need to validate?
I had exactly the same problem with the field getting correctly validated in TextBoxFor but not in DropDownListFor.
#Html.DropDownListFor(m => m.PaymentTO.CreditCardType, Model.CreditCardTypeList, "Select Card Type", new { style = "width:150px;" })
Since I had another DropDownListFor working on the same page, I knew that it wasn’t a generic DropDownListFor problem. I also have a complex model and parent object PaymentTO wasn’t initialized. When I set viewTO.PaymentTO = new PaymentTO(); in the Controller, the validation for the DropDownListFor started to work. So there is probably a problem with DropDownListFor, but the fix can be as simple as initializing the object in the controller.

Resources