nologo
nologo

Reputation: 6288

partialview model updating parent view

not sure how to word this correctly.. so i have a view which has a strongly typed viewmodel as:

class MyViewModel
{
    public string MyName get; set;
    public string DateOfBirth get; set;
    public Address MyAddress get; set;
}

class Address
{
    public string Street get; set;
    etc...
}

i'm loading the inital view with MyViewModel and using the following to display a partial view to load the address (this way so the address input can be reused).

the view contains a dropdown list with a list of user names in, selecting a value in the drop down calls a ajax .change function which does the following:

$.get('/User/DisplayAddress/', {'selection': selection }, function (html) {

$('#addressBlock').html(html);

});

that all works great..and the html is loaded in.. however, the viewmodel and the address is now disconnected. so when i submit my page, the MyAddress from the ViewModel now contains a null.

How should i be correctly doing this in mvc2 / ajax?

another approach i used was to use the '<% RenderPartial("viewname", Model.MyAddress); %> which works but i still have to return the data in json and add the values to the fields manually in a java function - this works well.. but its very messy when MyAddress field my contain several fields and to hardcode adding the value into the input fields just looks horrible.

Upvotes: 1

Views: 1040

Answers (1)

nologo
nologo

Reputation: 6288

the problem was the binding got screwed when insert the HTML from the partial. my partial view didnt follow the same namespace so the input fields lost the binding to the parentview model.

i.e. my textbox now has the naming convention MyViewModel.Address.Street etc.

i used the jquery approach to replace the div container with the HTML. the problem was the binding had got screwed when displaying the html.

i set up the 'name' element of the textboxes to use the same as the inputmodel and this kept the binding when inserting the partial.

ideally, i would use a 'flat' viewmodel instead of this 'inheritance' approach but i wasnt able to in this instance.

Upvotes: 1

Related Questions