Callbacks on Ajax.BeginForm don't work

2019-08-24 13:41发布

问题:

I'm having difficulty getting the callbacks to work for a form. I have something like this:

<script>
function VendorCreated() {
  alert('ok');
}
</script>

@using (Ajax.BeginForm("Create", "Vendor", new AjaxOptions {
    UpdateTargetId = ViewBag.TargetId, 
    HttpMethod = "Post", 
    OnSuccess="VendorCreated",
    })) {

upon submission my function never gets created. If I use:

OnSuccess="alert('ok')"

it works fine. I've also tried:

OnSuccess="function() { VendorCreated(); }"

but I get a runtime error. Others are having this issue but I've found no resolution, see MVC 3 Razor - Ajax.BeginForm OnSuccess and Ajax.BeginForm OnBegin confirmation Via jquery modal.

If I look at the IE debugger (F12) I don't see a script tag in the code generated... what's the right approach?

回答1:

ok, I've narrowed the problem down... the code above is generated by a view which gets loaded into a DIV in another view by jQuery. I've recently discovered that I can include a view within another view using @Html.Action() and doing so seems to resolve the problem above. I now get callbacks!

for anyone with the inclination, an explanation of why one works and not the other would be great.



回答2:

Are you including jquery.unobtrusive.ajax.js in your page?