jQuery ASP.NET MVC4 AJAX.BeginForm AjaxOptions OnSuccess 未调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19265605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:33:47  来源:igfitidea点击:

ASP.NET MVC4 AJAX.BeginForm AjaxOptions OnSuccess not called

javascriptjqueryajaxasp.net-mvc-4

提问by ravikumar

I'm trying to use Jquery Model Dialog in MVC4 using Razor dialog box showing fine but AjaxOptions.OnSuccess javascript function is not calling after i click the update button but it's redirected to http://<>:3738/Cars/Edit/1?Length=4 i don;t know why it was happened.

我试图在 MVC4 中使用 Jquery 模型对话框,使用 Razor 对话框显示正常,但 AjaxOptions.OnSuccess javascript 函数在我单击更新按钮后没有调用,但它被重定向到 http://<>:3738/Cars/Edit/1 ?Length=4 我不知道为什么会这样。

Here is my Code

这是我的代码

CarController.cs

汽车控制器.cs

public class CarsController : Controller
{
    private ExpDb db = new ExpDb();

    //
    // GET: /Cars/

    public ActionResult Index()
    {
        return View(db.Cars.ToList());
    }



    //
    // GET: /Cars/Edit/5

    public ActionResult Edit(int id = 0)
    {
        CarModel carmodel = db.Cars.Find(id);
        if (carmodel == null)
        {
            return HttpNotFound();
        }
        return PartialView(carmodel);
    }

    //
    // POST: /Cars/Edit/5

    [HttpPost]
    public JsonResult  Edit(CarModel carmodel)
    {
        if (ModelState.IsValid)
        {

            db.Entry(carmodel).State = EntityState.Modified;
            db.SaveChanges();
            //return RedirectToAction("Index");
             return Json(JsonResponseFactory.SuccessResponse(carmodel),JsonRequestBehavior.DenyGet);
        }
      else {
            return Json(JsonResponseFactory.ErrorResponse("Please review your form"), JsonRequestBehavior.DenyGet);
        }
    }

Index.cshtml

索引.cshtml

@model IEnumerable<AjaxSamples.Models.CarModel>

@{
ViewBag.Title = "Index";
}
<div id="commonMessage"></div>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
    <th>
        @Html.DisplayNameFor(model => model.ImageFileName)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Name)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Description)
    </th>
    <th></th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.ImageFileName)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Description)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = item.Id }, new { @class = "editLink" }) |
        @Html.ActionLink("Details", "Details", new { id=item.Id }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.Id })

        <button id="opener">Open Dialog</button>
    </td>
  </tr>



 }

</table>

 <div id="updateDialog" title="Update Car"></div>
 <script type="text/javascript">
 var linkObj;
 $(function () {
    $(".editLink").button();

    $('#updateDialog').dialog({
        autoOpen: false,
        width: 400,
        resizable: false,
        modal: true,
        buttons: {
            "Update": function () {
                $("#update-message").html(''); //make sure there is nothing on the message before we continue                         
                $("#updateCarForm").submit();
            },
            "Cancel": function () {
                alert('sd');
                $(this).dialog("close");
            }
        }
    });

    $(".editLink").click(function () {
        //change the title of the dialog
        linkObj = $(this);
        var dialogDiv = $('#updateDialog');
        var viewUrl = linkObj.attr('href');
        $.get(viewUrl, function (data) {
            alert(data);
            dialogDiv.html(data);
            //validation
            var $form = $("#updateCarForm");
            // Unbind existing validation
            $form.unbind();
            $form.data("validator", null);
            // Check document for changes
            $.validator.unobtrusive.parse(document);
            // Re add validation with changes
            $form.validate($form.data("unobtrusiveValidation").options);
            //open dialog
            dialogDiv.dialog('open');
        });
        return false;
    });

});
function err(data) {
    alert(data);
}


 function updateSuccess(data) {
    alert(data);
}

Edit.cshtml

编辑.cshtml

@model AjaxSamples.Models.CarModel

@{
ViewBag.Title = "Edit";
}

@using (Ajax.BeginForm("Edit", "Cars", new AjaxOptions
    {
        InsertionMode = InsertionMode.Replace, 
        HttpMethod = "POST",
        OnSuccess = "updateSuccess"
    }, new { @id = "updateCarForm" }))
 {
 @Html.ValidationSummary(true)
<div id="update-message" class="error invisible"></div>
<fieldset>
    <legend>CarModel</legend>

    @Html.HiddenFor(model => model.Id)

    <div class="editor-label">
        @Html.LabelFor(model => model.ImageFileName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.ImageFileName)
        @Html.ValidationMessageFor(model => model.ImageFileName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Description)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Description)
        @Html.ValidationMessageFor(model => model.Description)
    </div>

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

回答by maxspan

The below Jquery File is required

需要以下 Jquery 文件

jquery.unobtrusive-ajax.js

jquery.unobtrusive-ajax.js

回答by Sam

The problem I was having is that I was declaring the success function inside $(document).ready(). I moved it outside and it worked.

我遇到的问题是我在 $(document).ready() 中声明了成功函数。我把它搬到外面,它奏效了。

i.e.:

IE:

@using (Ajax.BeginForm("DialogTest", "Main", new AjaxOptions { HttpMethod = "Post", OnSuccess = "ajaxSuccess" }))
{
    <input type="button" id="info" value="Info" />
    <input type="button" id="confirm" value="Confirm" />
    <input type="button" id="wait" value="Wait" />
    <input type="button" id="ask" value="Ask" />
    <br /><br />
    <input type="submit" value="Submit" />
}



@section Scripts
{
    <script type="text/javascript">

        var ajaxSuccess = function () {
            alert('this is ajaxSuccess');
        }


        $(document).ready(function () {
            // do not declare ajaxSuccess here

            $('#mainForm').submit(function () {
                radarApp.InfoDialog("form submitted.");
                return false;
            });

// snip

回答by Alex

You need to add one more parameter in your BeginForm call:

您需要在 BeginForm 调用中再添加一个参数:

Ajax.BeginForm("Edit","Cars", null, new AjaxOptions
               {
                   InsertionMode = InsertionMode.Replace,
                   HttpMethod = "POST",
                   OnSuccess = "updateSuccess"
               }, new { @id = ""updateCarForm })

nullis for RouteValueDictionary. Hereare all overloads for Ajax.BeginForm method.

null用于 RouteValueDictionary。这里是 Ajax.BeginForm 方法的所有重载。

回答by RestoreProSoftware

I had the same issue. Initially I had my script in the head section of the partial view... This was causing my issues.

我遇到过同样的问题。最初我在局部视图的头部部分有我的脚本......这导致了我的问题。

I moved it to the header in view that was hosting my partial view and everything worked fine. My view is a bootstrap page hosted in a mvc application with the layout set to: "Layout = Nothing". If your controller action is loading a view, there is definitely a issue with the jquery.unobtrusive-ajax.js location...

我将它移到了托管我的部分视图的视图的标题中,并且一切正常。我的视图是托管在 mvc 应用程序中的引导程序页面,其布局设置为:“Layout = Nothing”。如果您的控制器操作正在加载视图,则 jquery.unobtrusive-ajax.js 位置肯定存在问题...

回答by Cadete

Try:

尝试:

@using (Ajax.BeginForm("Edit", new {controller = "Cars"}, new AjaxOptions

@using (Ajax.BeginForm("Edit", new {controller = "Cars"}, new AjaxOptions

回答by rexcfnghk

There is a syntax error in @Alex's code, this should be working:

@Alex 的代码中存在语法错误,这应该可以正常工作:

Ajax.BeginForm("Edit","Cars", null, new AjaxOptions
           {
               InsertionMode = InsertionMode.Replace,
               HttpMethod = "Post",
               OnSuccess = "updateSuccess"
           }, new { id = "updateCarForm" })
{ /* Razor code */ }

Specifically you should be looking at thisoverload of Ajax.BeginForm().

具体来说,你应该寻找在这个过载Ajax.BeginForm()

回答by Anand Thakkar

You can use Post method directly inside the Script tag for call the controller method like :

您可以直接在 Script 标签内使用 Post 方法来调用控制器方法,例如:

@using (Html.BeginForm("Edit", "Cars", FormMethod.Post, new { id = "updateCarForm" }))
{
  .......Yourdata......
}

and then in the Jquery

然后在 Jquery 中

function PostForm(url) {
    $("#updateCarForm").valid();
    if ($("#updateCarForm").valid()) {
    $.post(url, $("#updateCarForm").serialize(), function (data) { updateSuccess(data); });
    }
}