3
votes

I use a view with two partial views inside.

<div id="matches">
    <% foreach (var item in Model)
       { %>
    <% Html.RenderPartial("RenderMatchesListRowUserControl", item); %>
    <% } %>
</div>
<div id="addMatchFormBox">    
    <% Html.RenderPartial("AddNewMatchUserControl");%>
</div>

The first partial view "RenderMatchesListRowUserControl" renders a simple div element (for a list of matches), the second one "AddNewMatchUserControl" renders a form to create a new match beneath the list:

Source of AddNewMatchUserControl:

<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>

<% using (Ajax.BeginForm("Create", new AjaxOptions
   {
       UpdateTargetId = "matches",
       InsertionMode = InsertionMode.InsertAfter,
       OnSuccess = "flashit",
       OnFailure = "renderForm"
   }))
   {%>
<fieldset>
    <legend>New Match</legend>
    <p>
        <label for="DurationBetweenMovesInDays">
            Dauer (in Tagen) zwischen den Z&uuml;gen:</label>
        <%= Html.TextBox("DurationBetweenMovesInDays")%>
        <%= Html.ValidationMessage("DurationBetweenMovesInDays", "*")%>
    </p>
    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
<% } %>

Depending on the ModelState, the controller returns the partial view for the new match entry or the partial view for the form, to display the model errors.

if (Request.IsAjaxRequest()) {
            return ModelState.IsValid ?    PartialView("RenderMatchesListRowUserControl", match) : PartialView("AddNewMatchUserControl");
        }

It works fine, till the ModelState become invalid. In this case the form will be rendered at the end of the matches list because of the updatetargetid refers to the div element which contains the matches list. To avoid this, the updatetargetid must be changed to refer the div element containing the form. But i have no idea how to do this.

2

2 Answers

0
votes

I have the same problem. I want to update content in a div which contain a form if a model state is invalid and update a collection of data if it is successfully saved. So the trick I use is instead of using "UpdateTargetId". I use "OnSuccess" to handler it.

Here is an example.

    @using (Ajax.BeginForm("SaveUser", new AjaxOptions{
HttpMethod = "Post",
LoadingElementId = "save-progress",
OnSuccess = "onUpdateSuccess"
InsertionMode = InsertionMode.Replace}))

Here is a javascript example.

function onUpdateSuccess(response, xhr) {
     $('#progress-bar').css({ 'display': 'none' });
     if (response.indexOf('form') != -1) {
        $('#addOrEditUserForm').html(response);

     } else {
       $('#user-table').html(response);
       $('#addOrEditUserForm').html('')
 }

};

-3
votes

OKay. There is no way to achieve this in that way. I solved it with jQuery.