Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 未调用ASP.NET MVC4 AJAX.Begin AjaxOptions OnSuccess_Javascript_Jquery_Ajax_Asp.net Mvc 4 - Fatal编程技术网

Javascript 未调用ASP.NET MVC4 AJAX.Begin AjaxOptions OnSuccess

Javascript 未调用ASP.NET MVC4 AJAX.Begin AjaxOptions OnSuccess,javascript,jquery,ajax,asp.net-mvc-4,Javascript,Jquery,Ajax,Asp.net Mvc 4,我试图在MVC4中使用Jquery模型对话框,使用Razor对话框显示精细但AjaxOptions.OnSuccess javascript函数在我单击更新按钮后没有调用,但它被重定向到http://:3738/Cars/Edit/1?Length=4 I don;我不知道为什么会这样 这是我的密码 CarController.cs public class CarsController : Controller { private ExpDb db = new ExpDb();

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

这是我的密码

CarController.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

@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);
}
@model IEnumerable
@{
ViewBag.Title=“Index”;
}

@ActionLink(“新建”、“创建”)

@Html.DisplayNameFor(model=>model.ImageFileName) @DisplayNameFor(model=>model.Name) @DisplayNameFor(model=>model.Description) @foreach(模型中的var项目){ @DisplayFor(modelItem=>item.ImageFileName) @DisplayFor(modelItem=>item.Name) @DisplayFor(modelItem=>item.Description) @ActionLink(“编辑”,“编辑”,新的{id=item.id},新的{@class=“editLink”})| @ActionLink(“详细信息”,“详细信息”,新的{id=item.id})| @ActionLink(“删除”,“删除”,新的{id=item.id}) 打开对话框 } var-linkObj; $(函数(){ $(“.editLink”).button(); $('#updateDialog')。对话框({ 自动打开:错误, 宽度:400, 可调整大小:false, 莫代尔:是的, 按钮:{ “更新”:函数(){ $(“#更新消息”).html(“”);//继续之前,请确保消息中没有任何内容 $(“#updateCarForm”).submit(); }, “取消”:函数(){ 警报(“sd”); $(此).dialog(“关闭”); } } }); $(“.editLink”)。单击(函数(){ //更改对话框的标题 linkObj=$(本); var dialogDiv=$('#updateDialog'); var viewUrl=linkObj.attr('href'); $.get(视图URL、函数(数据){ 警报(数据); dialogDiv.html(数据); //验证 var$form=$(“#updateCarForm”); //取消绑定现有验证 $form.unbind(); $form.data(“验证器”,空); //检查文档是否有更改 $.validator.unobtrusive.parse(文档); //使用更改重新添加验证 $form.validate($form.data(“unobtrusiveValidation”).options); //打开对话框 dialogDiv.dialog(“打开”); }); 返回false; }); }); 函数错误(数据){ 警报(数据); } 函数updateSuccess(数据){ 警报(数据); }

Edit.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>
@model AjaxSamples.Models.CarModel
@{
ViewBag.Title=“编辑”;
}
@使用(Ajax.BeginForm(“编辑”,“汽车”,新的AjaxOptions
{
InsertionMode=InsertionMode.Replace,
HttpMethod=“POST”,
OnSuccess=“updateSuccess”
},新的{@id=“updateCarForm”})
{
@Html.ValidationSummary(true)
卡莫德尔
@Html.HiddenFor(model=>model.Id)
@Html.LabelFor(model=>model.ImageFileName)
@Html.EditorFor(model=>model.ImageFileName)
@Html.ValidationMessageFor(model=>model.ImageFileName)
@LabelFor(model=>model.Name)
@EditorFor(model=>model.Name)
@Html.ValidationMessageFor(model=>model.Name)
@LabelFor(model=>model.Description)
@EditorFor(model=>model.Description)
@Html.ValidationMessageFor(model=>model.Description)

} @ActionLink(“返回列表”、“索引”)
您可以在脚本标记内直接使用Post方法调用控制器方法,如:

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

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

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

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

null
用于RouteValueDictionary。都是Ajax.BeginForm方法的重载。

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

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

具体地说,您应该关注Ajax.BeginForm()的重载问题。我也有同样的问题。最初我的脚本在局部视图的头部部分。。。这导致了我的问题

我把它移到了视图中的标题,它承载了我的部分视图,一切都很好。我的视图是mvc应用程序中托管的引导页面,布局设置为:“布局=无”。如果您的控制器操作正在加载视图,那么jquery.unobtrusive-ajax.js位置肯定有问题


需要以下Jquery文件

jquery.unobtrusive-ajax.js

试试:


@使用(Ajax.beginnform(“Edit”),new{controller=“Cars”},new AjaxOptions

我遇到的问题是,我在$(document).ready()中声明了成功函数。我将它移到了外部,它成功了

i、 e:

@使用(Ajax.BeginForm(“DialogTest”、“Main”、新的AjaxOptions{HttpMethod=“Post”、OnSuccess=“ajaxSuccess”}))
{


} @节脚本 { var ajaxSuccess=函数(){ 警报(“这是ajaxSuccess”); } $(文档).ready(函数(){ //不要在此声明ajaxSuccess $('#mainForm')。提交(函数(){ radarApp.InfoDialog(“提交的表格”); 返回false; }); //剪断
你在jquery.js之后添加了jquery.unobtrusive-ajax.js吗?是的,我在_Layout.cshtmlHave中添加了它。你知道问题出在哪里了吗?我在自己的应用程序中也遇到了同样的问题。谢谢你的快速回复。但是当前代码中的实际问题是什么。你为什么要更改OP的
ajax.BeginForm()
Html.BeginForm()
?在我的建议中,我没有使用Ajax,我建议他使用Post方法的另一种解决方案,我将
Html.BeginForm()
放在那里。谢谢
@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