I have an MVC3 razor project, which I am trying to build using multiple reusable elements. I have many model classes like the following
public class ProductCreateModel
{
[Required]
[Display(Name = "Org")]
[UIHint("MyOrgsDropDown")]
public string orgName { get; set; }
[Required(ErrorMessage = "Select an account")]
[Display(Name = "Account")]
[UIHint("MyAccountsDropDown")]
[AdditionalMetadata("orgFieldId", "orgName")]
[AdditionalMetadata("fieldId", "accountName")]
public string accountName { get; set; }
}
There are other fields which I am omitting for this example
MyAccountsDropDown.cshtml looks like this:
@{
var values = ViewData.ModelMetadata.AdditionalValues;
string orgFieldId = (string)values["orgFieldId"];
string fieldId = (string)values["fieldId"];
}
<script type="text/javascript">
$(document).ready(function () {
$("#@orgFieldId").change(function () {
var idProd = $(this).val();
$.getJSON("/JsonService/GetAccounts", { orgId: idProd },
function (myData) {
var select = $("#@fieldId");
select.empty();
$.each(myData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
});
});
});
</script>
@Html.DropDownList("", new SelectList(Enumerable.Empty<SelectListItem>(), "Value", "Text"), "---Select---", new { id = fieldId })
My Controller methods look like this:
[HttpGet]
public ActionResult AddProduct()
{
return PartialView("_AddProduct");
}
[HttpPost]
public ActionResult AddProduct(ProductCreateModel model)
{
if (!ModelState.IsValid)
{
return PartialView("_AddProduct", model);
}
//do some stuff
return PartialView("_AddProduct");
}
So when the view opens (as a jQuery dialog box), I have the form all set. If I select an orgName, it pulls the accountName from the database (cascading). Now since I am using model validation, when I DO NOT fill in all the required fields, and press submit, it shows me the validation messages. It also shows me the pre-filled values of the fields I had already entered before submit. What is removes are the cascaded drop down values. So it continues to show the selected orgName, but the accountName drop down loses the previously filled values from the database.
How can I maintain the already pulled SelectItems from before the submit was clicked
Change the code in your javascript section to: