0

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

查询:

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

4 回答 4

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
});
于 2013-03-29T14:59:15.840 回答
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);
          }
        }
});
于 2013-03-29T15:01:22.833 回答
1

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

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

return this.Json(new { customerId = cust.customer_id});
于 2013-03-29T15:01:13.440 回答
0

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

你的控制器编译了吗?您的 post 方法具有 void 返回类型,因此当它看到返回 ID 并返回“错误”命令时,它应该无法编译

于 2013-03-29T15:00:04.047 回答