How to do MVC model binding with dynamically loaded form elements
Say I have a view model like this
class MyView
{
DynamicViewModel MyDynamicViewModel {get; set;}
}
class DynamicViewModel
{
string A {get; set;};
}
And on the actual view markup, I load MyView. I have an EditorTemple
partial view for DynamicViewModel because I want it to be reusable and it
also has some dynamic elements itself.
Also, the MyView page has it's own form elements that determine the
contents of MyDynamicViewModel. So depending on what the user
types/clicks, MyDynamicViewModel will be reloaded with new info via ajax
callbacks.
This works, but since DynamicViewModel is loaded dynamically, the MVC
model binder has no way of knowiing that the values in the
DynamicViewModel belong to the model on MyView.MyDynamicViewModel.
To illustrate, the form value for MyDynamicViewModel.A will have it's form
ID equal to "A". But to model bind, I need it to be MyDynamicViewModel.A,
like this:
<input id="MyDynamicViewModel.A" name="MyDynamicViewModel.A" type="text">
But this template gets loaded via ajax (the controller method returns the
view as string and the javascript just updates a div with the contents),
it doesn't know about the "owner" model MyView
No comments:
Post a Comment