将列表传递给控制器​​Asp.Net MVC Json

时间:2018-02-11 06:28:39

标签: c# asp.net json asp.net-mvc list

我有问题将列表数据从JS传递到Controller,因为列表是stringify,ajax没有提交给Controller。我应该对javascript和控制器方法做些什么改变呢。任何帮助,链接以实现它。

的Javascript

 $('#submit').click(function () {
    var isAllValid = true;
    var list = [];

        var orderItem = {

            Agency: $('.AgentName', this).val(),
            SectorPair: $('select.sectorCategory', this).val().trim(),
            ForPAX: $('.foreignPax', this).val(),
            IndPAX: $('.indianPax', this).val(),
            FlightDate: $('.flightDate', this).val(),
            Airlines: $('select.airlineCategory', this).val().trim()
        }
        list.push(orderItem);
        //}
    })

        $.ajax({
            type: 'POST',
            url: '/DomesticDeparture/Create',
            data: JSON.stringify(list),
            contentType: 'application/json',
            success: function (data) {
                if (data.status) {
                    alert('Successfully saved');
                    //here we will clear the form
                    list = [];
                    $('#airlineName,#departureDate').val('');
                    $('#orderdetailsItems').empty();
                    $('#AgentName').focus();
                }
                else {
                    alert('Error');
                }
                $('#submit').text('Save');
            },
            error: function (error) {
                console.log(error);
                $('#submit').text('Save');
            }
        });
    }

});

控制器

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create( List<DomesticDepartureEntry> dentries)
{
    if (ModelState.IsValid)
    {
       foreach (var a in dentries)
            {
                db.DomesticDepartureEntries.AddRange(dentries);
                db.SaveChanges();
            }
    }

    return View();
}

1 个答案:

答案 0 :(得分:0)

制作如下控制器的API控制器:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class ValuesController : ApiController
{
        [HttpPost]
        [Route("api/CreateRecord")]
        public async Task<HttpResponseMessage> CreateRecord([FromBody] List<DomesticDepartureEntry> dentries)
        {
            try
            {
               if (ModelState.IsValid)
               {
                  db.DomesticDepartureEntries.AddRange(dentries);
                  db.SaveChanges();
                  return new HttpResponseMessage()
                {
                    Content = new ObjectContent<JObject>(new JObject { new JProperty("message", "Record successfully inserted into the database!") }, new JsonMediaTypeFormatter()),
                    StatusCode = HttpStatusCode.OK
                };

               }
            }
            catch(Exception ex)
            {
               return new HttpResponseMessage()
                {
                    Content = new ObjectContent<JObject>(new JObject { new JProperty("message", $"Failed because: {ex.Message}") }, new JsonMediaTypeFormatter()),
                    StatusCode = HttpStatusCode.ExpectationFailed
                };
            }
        }
}

您不会将视图返回给AJAX成功回调,而是将JSON对象与状态代码一起返回给回调。

修改您的AJAX调用以将其路由到以下Web API:

$.ajax({
        method: 'POST',
        url: 'api/CreateRecord',
        data: JSON.stringify(list),
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (data)
        {
              if(!$.isEmptyObject(data)){
                console.log( data["message"] );
                alert( data["message"]);

                //Your business logic
                //here we will clear the form
                list = [];
                $('#airlineName,#departureDate').val('');
                $('#orderdetailsItems').empty();
                $('#AgentName').focus();
             }
            else
                 alert('Some error occured!');
        },
        error: function ( jqXHR, errorThrown, statusText )
        {
                console.log( errorThrown );
                alert(errorThrown);
        }
    });