ASP.Net MVC从AJAX帖子获取新添加记录的ID

时间:2013-03-29 14:53:56

标签: asp.net asp.net-mvc asp.net-mvc-3 jquery

在以下JQuery / Ajax发布后,如何从以下模型中检索 ID

JQuery的:

       $.ajax({
            type: 'POST',
            url: '/api/searchapi/Post',
            contentType: 'application/json; charset=utf-8',
            data: toSend,
        }).done(function (msg) {
                alert( "Data Saved: " + msg );
        });

控制器:

    // POST api/searchapi
    public Void Post(Booking booking)
    {
        if (ModelState.IsValid)
        {
            tblCustomerBooking cust = new tblCustomerBooking();
            cust.customer_email = booking.Email;
            cust.customer_name = booking.Name;
            cust.customer_tel = booking.Tel;

            bc.tblCustomerBookings.Add(cust);
            bc.SaveChanges();

            long ID = cust.customer_id;

            Return ID;   <-- what do I enter here?
         }

         Return "Error";  <-- and here?
     }  

如何将ID返回到jQuery脚本中,如果模型无效,如何将错误返回给jQuery?

感谢您的帮助,

标记

4 个答案:

答案 0 :(得分:3)

您可以返回JsonResult

[HttpPost]
public ActionResult Post(Booking booking)
{
    if (ModelState.IsValid)
    {
        tblCustomerBooking cust = new tblCustomerBooking();
        cust.customer_email = booking.Email;
        cust.customer_name = booking.Name;
        cust.customer_tel = booking.Tel;

        bc.tblCustomerBookings.Add(cust);
        bc.SaveChanges();

        return Json(new { id = cust.customer_id });
     }

     return HttpNotFound();
 }  

然后在客户端上简单地说:

$.ajax({
    type: 'POST',
    url: '/api/searchapi/Post',
    contentType: 'application/json; charset=utf-8',
    data: toSend,
}).done(function (msg) {
    alert('Customer id: ' + msg.id);
}).error(function(){
    // do something if the request failed
});

答案 1 :(得分:3)

一种方法是这样的:

在您的控制器中:

 public Void Post(Booking booking)
    {

         //if valid
         return Json(new {Success = true, Id = 5}); //5 as an example

         // if there's an error
         return Json(new {Success = false, Message = "your error message"}); //5 as an example
     }  

在你的ajax帖子中:

$.ajax({
        type: 'POST',
        url: '/api/searchapi/Post',
        contentType: 'application/json; charset=utf-8',
        data: toSend,
        success: function(result) {
          if (result.Success) {
            alert(result.Id);
          }
          else {
            alert(result.Message);
          }
        }
});

答案 2 :(得分:1)

返回void不是一个好主意,请使用JsonResult

因为您使用的是JavaScript,所以我建议您使用JSON。

return this.Json(new { customerId = cust.customer_id});

答案 3 :(得分:0)

为了接收返回值,控制器方法必须返回void之外的其他内容。

你的控制器是否编译?你的post方法有一个void返回类型,所以当它看到返回ID并返回“Error”命令时它应该会失败编译