简体   繁体   English

控制器已将传递给SQL Server的参数Ajax插入控制器后,如何从MVC控制器向Ajax发送成功消息

[英]How to send a success message from MVC controller to Ajax after the controller has inserted parameters Ajax passed to into SQL Server

JavaScript: JavaScript:

$("#button").click(function () {
    $.ajax({
        type: "POST",
        url: "controller/SaveSelection",
        data: {
            "Date": "date",
            "DataType": "type",
            "Id": "1234",
            "Name": "name"
        },
        success:function(){
            alert("Your selections have been saved");//never returned
        },
        error: function () {
            alert("failed");//always return this one, even it's succeed
        }
    });
});

C# Controller: C#控制器:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SaveSelection(Mytable obj) 
{
    try
    {
        _dataContext.Mytable.InsertOnSubmit(obj);
        _dataContext.SubmitChanges();
    }
    catch
    {
        return View();
    }

    return View();
}

The controller can successfully insert the AJAX parameters into a SQL Server table. 控制器可以成功地将AJAX参数插入SQL Server表中。 But in the frontend returns 500, apparently because I'm not requiring a data callback. 但是在前端返回500,显然是因为我不需要数据回调。

But is there a way to let the controller tell the JS that "Hey, I have successfully inserted those data you passed to me" so that the JS can return a success message in the browser? 但是,是否有一种方法可以让控制器告诉JS:“嘿,我已经成功插入了传递给我的数据”,以便JS可以在浏览器中返回成功消息?

Trying changing your method to an actionResult or JsonResult: 尝试将您的方法更改为actionResult或JsonResult:

    public ActionResult SaveSelection(Mytable obj)
    {
        try 
        {
          ....logic here....
          return Json("Your selections have been saved.", JsonRequestBehavior.AllowGet);
        }
        catch (Exception ex)
        {
            //TODO: log exception
            return new HttpStatusCodeResult(401, ex.Message);
        }
    }

As dave pointed out, you could also return like this instead: 正如dave所指出的,您也可以像这样返回:

return Content(jsonObject.ToString(), "application/json");

or 要么

return Content("Your message",...

Then in your ajax call change the success to: 然后在您的ajax调用中将成功更改为:

success: function(json) {
     alert(json);
}
error: function (event) {
            alert(event.statusText);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM