Search code examples
ajaxasp.net-mvcasp.net-mvc-3asp.net-mvc-ajax

Ajax.BeginForm with UpdateTarget Inside AjaxForm


Is this possible to use Ajax.Beginform with update target inside of ajax form. like this:

 using(Ajax.BeginForm("EditPhone", new { id = item.Id.Value }, new AjaxOptions {
       UpdateTargetId = "TRTarget"})) {
    <tr class="gradeA odd" id="TRTarget">
        <input type"submit" value="submit" />
    </tr>
}

Update

OK if it's possible so what is wrong with this?

This is my partial view that another partial view rendered inside it:

 using(Ajax.BeginForm("EditPhone", new { id = item.Id.Value }, new AjaxOptions {
       UpdateTargetId = "TRTarget"})) {
    <tr class="gradeA odd" id="TRTarget">
        @{Html.RenderPartial("_PhoneRow", item);}
    </tr>
}

and _PhoneRow:

@model MyModel
<td>@Html.DisplayFor(model=>model.Number)</td>
<td>@Html.DisplayFor(modelItem => Model.PhoneKind)</td>
<td><input type="submit" value="Edit" class="button" /></td>

And EditPhone Action:

public ActionResult EditPhone(long Id){

  //Get model
  return PartialView("_EditPhoneRow", model);
}

And _EditPhoneRow:

<td>@Html.EditorFor(model => model.MainModel.Number)</td>
<td>@Html.EditorFor(model => model.MainModel.PhoneKind)</td>
<td><input type="submit" value="Save" class="button" /></td>

Actually each of my rows have an Ajax form so when click on edit I want to replace the row with another as you see, but when I add the Edit, all of my page destroyed and just _EditPhoneRow shown like I select all page for updateTrget where is the problem? and what is your suggestion to change all the specific row like this?


Solution

  • According to the HTML specification forms cannot be nested. This produces invalid HTML and depending on the user agent either the outer or the inner <form> simply won't work. That's a limitation of the HTML specification, don't be confused with ASP.NET MVC, it has nothing to do with it. One possibility is to replace your Ajax.BeginForm with an Ajax.ActionLink:

    <tr class="gradeA odd" id="TRTarget">
        @Ajax.ActionLink(
            "Submit", 
            "EditPhone", 
            new { id = item.Id.Value }, 
            new AjaxOptions { UpdateTargetId = "TRTarget" }
        )
    </tr>
    


    UPDATE:

    After you have updated your question and explained the symptoms I think you might have forgotten to reference the jquery.unobtrusive-ajax.min.js script to your page:

    <script type="text/javascript" src="@Url.Content("~/scripts/jquery.unobtrusive-ajax.min.js")"></script>
    

    If you don't include this script the Ajax.* helpers such as Ajax.BeginForm and Ajax.ActionLink will be simple HTML forms and anchors. No AJAX at all. It is this script that reads the HTML5 data-* attributes emitted by those helpers and unobtrusively AJAXifies them.