mvc4 jquery.ajax成功未触发

mvc4 jquery .ajax success not fired

本文关键字:成功 jquery ajax mvc4      更新时间:2023-09-26

我有一个视图,其中有一个局部视图。我还有一个对控制器的ajax调用,它只更新我的模型而不返回视图。假设我需要单击网格上生成id的工具栏按钮。现在我想将该id返回到视图(通过使用该id更新模型)。但成功(数据)不是发射

$.ajax({
            type: "POST",
            data: JSON.stringify({ Id: pId, schId: sId}),
            contentType: "application/json; charset=utf-8",
            dataType: "JSON",
            cache: false,
            url: '@(Url.Action("Process", "Controller"))',
            success: function (data) {
                var abc = data.InvoiceId;---->not fired
            },
        });

控制器

public ActionResult Process(int Id, int schId, SearchModel mymodel, [DataSourceRequest]DataSourceRequest request)
        {
            int myId = -1;
                // generate the Id);
        myId = generatenewId(Id,schId);-- this gets generated and myId is updated
            }
            mymodel.Id = myId 
            return View(mymodel)
        }

您应该决定是要发送HTML结果(视图)还是JSON结果(JSON),并在Action中调用相应的结果。如果在jQueryAjax调用中将dataType设置为JSON,则应该返回JSON结果,例如:

public ActionResult Process(int Id, int schId, SearchModel mymodel, [DataSourceRequest]DataSourceRequest request)
{
  int myId = -1;
  // generate the Id);
  myId = generatenewId(Id,schId);-- this gets generated and myId is updated
  mymodel.Id = myId 
  return Json(mymodel) // this will return Json in the response containing your model object
  //return View(mymodel) !!! This would return a full HTML response rendered with you model
}

这就是我使用邮件表单的方式!

看看我的控制器中的签名,我使用的是JsonResult,而不是ActionResult!此外,我返回的JSON不是视图!

return Json(result);

在我的控制器中

 public JsonResult AjaxMailer(MailerModel model)
 {
            Emailer mailer = new Emailer();
            JsonResult Jr = new JsonResult();
            string result = mailer.DispatchEmail(model.phone, model.name, model.message, model.email);
            return Json(result);
 }

我的视图中的Java脚本

function imClicked(e) {
    e.preventDefault();
    var messageObj = 
   {
       "name": "",
       "email": "",
       "phone": "",
       "message": "",
   };
    messageObj.name = $("#name").val();
    messageObj.email = $("#email").val();
    messageObj.phone = $("#phone").val();
    messageObj.message = $("#message").val();
    $.ajax({
        dataType: "json",
        contentType: 'application/json',
        type: 'POST',
        url: '/Contact/AjaxMailer',
        data: JSON.stringify(messageObj),
        error: printError,
        success: mailsent
    });
};