How will model binder deals with Readonly & disabled

2k views Asked by At

I have the following two items , one which is readonly:-

@Html.TextBoxFor(model => model.Technology.Tag, new 
        { @readonly = "readonly" })

While the other is Disabled:-

@Html.DropDownListFor(model => model.Customer.NAME, ((IEnumerable<TMS.Models.AccountDefinition>)ViewBag.Customers).Select(option => new SelectListItem
{
    Text = (option == null ? "None" : option.ORG_NAME),
    Value = option.ORG_NAME.ToString(),
    Selected = (Model != null) && (Model.Customer != null) & (option.ORG_NAME == Model.Customer.NAME)
}), "Choose...", new { disabled = "disabled" })

so will the asp.net mvc model binder bind the two items? , or it will ignore any read-only and any disabled fields ?

2

There are 2 answers

4
Maess On

It will bind them, but as long as you have populated them with the correct data, that shouldn't matter. Also, you can have your code that maps these models to the entity, assuming you are using view models, just ignore the values in question. Assuming this is a standard HTTP Post from the form, HTTP will not post disabled or readonly fields, which means they will be null or the default value in the model, so you need to account for that.

If you want the binder to ignore these values, use TextBox and DropDownList and make sure they are not named the same as your properties. If you do not use 'For' you will need to add code in the view to set the values.

0
TryingReallyHardToDoBetter On

ReadOnly text fields get bound.

I've been trying to find a way around the unbound dropdownboxfor values. Here's what I came up with:

 $('#xxx').change(function() {$(this).val(lastSel_xxx);}); 
var lastSel_xxx = $("#xxx option:selected").val();

Use the code above for each HTML element in your view (this will require you to document each ID output) and replace 'xxx' with the element name.

When a user selects another option besides the initial option selected, it reverts back to the original.

HOpe this helps!