ASP.Net MVC - How to associate control made visible by jquery action to web model
I have a DropDownList populated with countries.
When the user picks US I need to show dropdown with US states. If user picks CA - show dropdown with CA provinces...else show a TextBox. Depending on the country picked I hide/show using jQuery. That works ok. The problem is in the ActionResult when user submits.
Html.DropDownList("State", ViewData["States"] as SelectList,
new { @class = "states", @style = "display:none;" })
Html.DropDownList("State", ViewData["Provinces"] as SelectList,
new { @class = "provinces", @style = "display:none;" })
Html.TextBox("State", null, new { @class = "stateFreeForm" })
I pre-load the 2 dropdowns with US and CA data The web model has a string member called State but it is mapping to the first DropDownList (US states). So even though on the page I have a TextBox visible the listing.State member contains the data picked from the US dropdown. I'm using Validation and the State is required so I want to have just one State (not State, Province, Other). Is there something I can do in the jQuery to set change the mapping between web model and control.
I'd prefer to have the the dropdowns pre loaded and just toggle them via scripting rather make an ajax call to reload dropdowns etc.
p开发者_如何学Cublic ActionResult Post(MyApp.Web.Models.Listing listing)
{
}
Thanks...
There are a number of ways you could do this... But I think the quickest would be to modify your jQuery validation. If you're using the main jQuery Validation plugin, you can set it up to use dependent validation, so depending on what is selected for Country, you can validate a different field.
http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-expression
Just name 2nd select list to 'Province'. Do not confuse Yourself, framework and everyone else.
Or is there really really good reason not to do that?
I guess that i don't want to fix validation in order to fit business
doesn't counts.
精彩评论