Dynamically Generated Ajax.BeginForm

ⅰ亾dé卋堺 提交于 2020-01-06 19:54:30

问题


I have a problem with ASP.NET MVC Ajax forms. I generate several Ajax forms in a table, like this:

<% 
foreach (var item in Model)
       {
           var statefulItem = item as StatefulEffectiveItem; %>
    <tr>
        <td>
            <% using (Ajax.BeginForm("ShowAddActivity", "EffectiveItems", new { id = item.Id }, new AjaxOptions() { UpdateTargetId = "details", OnSuccess = "dialogIt" }))
               { %>
            <input type="submit" name="activity" value="Add Activity" />
            <% } %>
        </td>
    </tr>
    <% } %>

so far so good. When I post one of those forms, it renders a partial view in a div, and this new partial view contains a new Ajax.BeginForm (which is NOT nested in the originator form). This second Ajax.BeginForm is absolutely similar to the ones I generate in the table, but when I post it I don't get an "Ajax post", but a normal post which sends me to a new page. I don't understand what causes the difference between this two Ajax form, why this "dynamically generated" Ajax form behaves like a normal html form?

By the way, I know I can do this in different ways using Javascript, but I would like to understand if this can be done just using MVC helpers and Ajax Library and, if the answer is "yes", where I do wrong.

Thank you very much,

Wasp


回答1:


I don't know if it can be done with MS AJAX but I can tell you what is wrong. Once you update the partial on the first ajax, this updated partial contains javascript to register ajax for the new form. This javascript is not executed because there's nothing that is telling it to execute. You must call a javascript function that registers ajax for the second form on the success callback of the first ajax request.




回答2:


Edit the /scripts/jquery.unobtrusive-ajax.js file

Change

$("a[data-ajax=true]").on("click", function (evt) { ..... }

To

$(document).on("click","a[data-ajax=true]", function (evt) { ...... }

Do this for all other event registrations in the file.

$(document).on("click","form[data-ajax=true] input[type=image]"
$(document).on("click","form[data-ajax=true] :submit"
$(document).on("submit","form[data-ajax=true]", 

This way, you register the events to the document, which allows event handling for the dynamically added elements. jQuery was using ".live()" before, but now you can do this with adding event handlers to the document with the ".on()" method.



来源:https://stackoverflow.com/questions/2183475/dynamically-generated-ajax-beginform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!