복붙노트

[JQUERY] jQuery를 Ajax를 사용하여 MVC 컨트롤러 메서드에 개체의 목록을 전달

JQUERY

jQuery를 Ajax를 사용하여 MVC 컨트롤러 메서드에 개체의 목록을 전달

해결법


  1. 1.NickW의 제안을 사용하여, 나는 일 = JSON.stringify ({ '물건'일을})를 사용하여이 작업을 얻을 수 있었다; 여기에 전체 코드입니다.

    NickW의 제안을 사용하여, 나는 일 = JSON.stringify ({ '물건'일을})를 사용하여이 작업을 얻을 수 있었다; 여기에 전체 코드입니다.

    $(document).ready(function () {
        var things = [
            { id: 1, color: 'yellow' },
            { id: 2, color: 'blue' },
            { id: 3, color: 'red' }
        ];      
    
        things = JSON.stringify({ 'things': things });
    
        $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'POST',
            url: '/Home/PassThings',
            data: things,
            success: function () {          
                $('#result').html('"PassThings()" successfully called.');
            },
            failure: function (response) {          
                $('#result').html(response);
            }
        }); 
    });
    
    
    public void PassThings(List<Thing> things)
    {
        var t = things;
    }
    
    public class Thing
    {
        public int Id { get; set; }
        public string Color { get; set; }
    }
    

    나는이 배운 두 가지가 있습니다 :

    나는이 다른 사람을 도움이되기를 바랍니다!


  2. 2.당신은이 작업을 수행 할 수 있을까?

    당신은이 작업을 수행 할 수 있을까?

    var things = [
        { id: 1, color: 'yellow' },
        { id: 2, color: 'blue' },
        { id: 3, color: 'red' }
    ];
    $.post('@Url.Action("PassThings")', { things: things },
       function () {
            $('#result').html('"PassThings()" successfully called.');
       });
    

    ... 그리고 귀하의 조치를 표시

    [HttpPost]
    public void PassThings(IEnumerable<Thing> things)
    {
        // do stuff with things here...
    }
    

  3. 3.데이터를 포맷하면 문제가 될 수. 이 중 하나를 시도해보십시오

    데이터를 포맷하면 문제가 될 수. 이 중 하나를 시도해보십시오

    data: '{ "things":' + JSON.stringify(things) + '}',
    

    또는 (I 양식없이 ASP.NET MVC 컨트롤러에 문자열의 배열을 게시 할 수있는 방법은에서?)

    var postData = { things: things };
    ...
    data = postData
    

  4. 4.나는 닷넷 코어 2.1 웹 응용 프로그램을 사용하고 작업 여기에 하나의 답을 얻을 수 없었다. (방법이 전혀 호출 된 경우) 또는 500 서버 오류 나도 빈 매개 변수를 얻었다. 나는 대답의 모든 가능한 조합으로 연주하기 시작하고 마지막 작업 결과를 얻었다.

    나는 닷넷 코어 2.1 웹 응용 프로그램을 사용하고 작업 여기에 하나의 답을 얻을 수 없었다. (방법이 전혀 호출 된 경우) 또는 500 서버 오류 나도 빈 매개 변수를 얻었다. 나는 대답의 모든 가능한 조합으로 연주하기 시작하고 마지막 작업 결과를 얻었다.

    다음과 같이 내 경우에는 해결책이었다 :

        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: mycontrolleraction,
            data: JSON.stringify(things)
        });
    
        [HttpPost]
        public IActionResult NewBranch([FromBody]IEnumerable<Thing> things)
        {
            return Ok();
        }
    

  5. 5.나는 모든이에 대한 완벽한 해답을 가지고 내가하지, 아래에 상세 답을 찾을하시기 바랍니다 관리 마침내 자신이 할 수 얻을 수 많은 솔루션을 시도 :

    나는 모든이에 대한 완벽한 해답을 가지고 내가하지, 아래에 상세 답을 찾을하시기 바랍니다 관리 마침내 자신이 할 수 얻을 수 많은 솔루션을 시도 :

           $.ajax({
                traditional: true,
                url: "/Conroller/MethodTest",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data:JSON.stringify( 
                   [
                    { id: 1, color: 'yellow' },
                    { id: 2, color: 'blue' },
                    { id: 3, color: 'red' }
                    ]),
                success: function (data) {
                    $scope.DisplayError(data.requestStatus);
                }
            });
    

    제어

    public class Thing
    {
        public int id { get; set; }
        public string color { get; set; }
    }
    
    public JsonResult MethodTest(IEnumerable<Thing> datav)
        {
       //now  datav is having all your values
      }
    

  6. 6.나는 일이를 얻을 수있는 유일한 방법은 문자열로 JSON을 통과하고 그 MVC 4의 기본 디시리얼라이저 있다면 꽤 이상하다 JavaScriptSerializer.Deserialize (문자열 입력)를 사용하여 deserialise하는 것입니다.

    나는 일이를 얻을 수있는 유일한 방법은 문자열로 JSON을 통과하고 그 MVC 4의 기본 디시리얼라이저 있다면 꽤 이상하다 JavaScriptSerializer.Deserialize (문자열 입력)를 사용하여 deserialise하는 것입니다.

    내 모델은 중첩 된 객체의 목록과 내가 항목의 정확한 숫자를 가지고 최상단 목록을 JSON 데이터입니다 사용하여 얻을 수있는 최선을 가지고 있지만, 항목의 모든 필드가 null이었다.

    이런 종류의 일이 그렇게 어렵지 않을 것이다.

        $.ajax({
            type: 'POST',
            url: '/Agri/Map/SaveSelfValuation',
            data: { json: JSON.stringify(model) },
            dataType: 'text',
            success: function (data) {
    
        [HttpPost]
        public JsonResult DoSomething(string json)
        {
            var model = new JavaScriptSerializer().Deserialize<Valuation>(json);
    

  7. 7.이것은 당신이 그것을 사용할 수 있습니다, 귀하의 질의에 대한 코드를 노력하고 있습니다.

    이것은 당신이 그것을 사용할 수 있습니다, 귀하의 질의에 대한 코드를 노력하고 있습니다.

    제어

        [HttpPost]
        public ActionResult save(List<ListName> listObject)
        {
        //operation return
        Json(new { istObject }, JsonRequestBehavior.AllowGet); }
        }
    

    자바 스크립트

      $("#btnSubmit").click(function () {
        var myColumnDefs = [];
        $('input[type=checkbox]').each(function () {
            if (this.checked) {
                myColumnDefs.push({ 'Status': true, 'ID': $(this).data('id') })
            } else {
                myColumnDefs.push({ 'Status': false, 'ID': $(this).data('id') })
            }
        });
       var data1 = { 'listObject': myColumnDefs};
       var data = JSON.stringify(data1)
       $.ajax({
       type: 'post',
       url: '/Controller/action',
       data:data ,
       contentType: 'application/json; charset=utf-8',
       success: function (response) {
        //do your actions
       },
       error: function (response) {
        alert("error occured");
       }
       });
    

  8. 8.MVC의 컨트롤러 작동에 의해 예상되는 매개 변수의 이름과 일치하는 속성을 포함하는 다른 객체와 객체의 목록을 포장. 중요한 비트는 개체 목록 주위의 래퍼 인.

    MVC의 컨트롤러 작동에 의해 예상되는 매개 변수의 이름과 일치하는 속성을 포함하는 다른 객체와 객체의 목록을 포장. 중요한 비트는 개체 목록 주위의 래퍼 인.

    $(document).ready(function () {
        var employeeList = [
            { id: 1, name: 'Bob' },
            { id: 2, name: 'John' },
            { id: 3, name: 'Tom' }
        ];      
    
        var Employees = {
          EmployeeList: employeeList
        }
    
        $.ajax({
            dataType: 'json',
            type: 'POST',
            url: '/Employees/Process',
            data: Employees,
            success: function () {          
                $('#InfoPanel').html('It worked!');
            },
            failure: function (response) {          
                $('#InfoPanel').html(response);
            }
        }); 
    });
    
    
    public void Process(List<Employee> EmployeeList)
    {
        var emps = EmployeeList;
    }
    
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

  9. 9.

         var List = @Html.Raw(Json.Encode(Model));
    $.ajax({
        type: 'post',
        url: '/Controller/action',
        data:JSON.stringify({ 'item': List}),
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            //do your actions
        },
        error: function (response) {
            alert("error occured");
        }
    });
    

  10. 10.당신은 ASP.NET 웹 API를 사용하는 경우, 당신은 단지 데이터를 전달해야합니다 JSON.stringify (일을).

    당신은 ASP.NET 웹 API를 사용하는 경우, 당신은 단지 데이터를 전달해야합니다 JSON.stringify (일을).

    그리고 컨트롤러는 다음과 같이 보일 것입니다 :

    public class PassThingsController : ApiController
    {
        public HttpResponseMessage Post(List<Thing> things)
        {
            // code
        }
    }
    

  11. 11.@veeresh 전에서 수정

    @veeresh 전에서 수정

     var data=[
    
                            { id: 1, color: 'yellow' },
                            { id: 2, color: 'blue' },
                            { id: 3, color: 'red' }
                            ]; //parameter
            var para={};
            para.datav=data;   //datav from View
    
    
            $.ajax({
                        traditional: true,
                        url: "/Conroller/MethodTest",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        data:para,
                        success: function (data) {
                            $scope.DisplayError(data.requestStatus);
                        }
                    });
    
    In MVC
    
    
    
    public class Thing
        {
            public int id { get; set; }
            public string color { get; set; }
        }
    
        public JsonResult MethodTest(IEnumerable<Thing> datav)
            {
           //now  datav is having all your values
          }
    

  12. 12.MVC 액션에 DataTable을 여러 선택된 행에서 일부 데이터를 보내려고 할 때 내가 무슨 짓을 :

    MVC 액션에 DataTable을 여러 선택된 행에서 일부 데이터를 보내려고 할 때 내가 무슨 짓을 :

    HTML 페이지의 시작 부분에서 :

    @Html.AntiForgeryToken()
    

    (단지 행 바인드 모델 나타낸다)

     @foreach (var item in Model.ListOrderLines)
                    {
                        <tr data-orderid="@item.OrderId" data-orderlineid="@item.OrderLineId" data-iscustom="@item.IsCustom">
                            <td>@item.OrderId</td>
                            <td>@item.OrderDate</td>
                            <td>@item.RequestedDeliveryDate</td>
                            <td>@item.ProductName</td>
                            <td>@item.Ident</td>
                            <td>@item.CompanyName</td>
                            <td>@item.DepartmentName</td>
                            <td>@item.ProdAlias</td>
                            <td>@item.ProducerName</td>
                            <td>@item.ProductionInfo</td>
                        </tr>
                    }
    

    자바 스크립트 기능을 시작 버튼 :

     <button class="btn waves-effect waves-light btn-success" onclick="ProcessMultipleRows();">Start</button>
    

    자바 스크립트 기능 :

      function ProcessMultipleRows() {
                if ($(".dataTables_scrollBody>tr.selected").length > 0) {
                    var list = [];
                    $(".dataTables_scrollBody>tr.selected").each(function (e) {
                        var element = $(this);
                        var orderid = element.data("orderid");
                        var iscustom = element.data("iscustom");
                        var orderlineid = element.data("orderlineid");
                        var folderPath = "";
                        var fileName = "";
    
                        list.push({ orderId: orderid, isCustomOrderLine: iscustom, orderLineId: orderlineid, folderPath: folderPath, fileName : fileName});
                    });
    
                    $.ajax({
                        url: '@Url.Action("StartWorkflow","OrderLines")',
                        type: "post", //<------------- this is important
                        data: { model: list }, //<------------- this is important
                        beforeSend: function (xhr) {//<--- This is important
                          xhr.setRequestHeader("RequestVerificationToken",
                          $('input:hidden[name="__RequestVerificationToken"]').val());
                          showPreloader();
                        },
                        success: function (data) {
    
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
    
                        },
                         complete: function () {
                             hidePreloader();
                        }
                    });
                }
            }
    

    MVC 액션 :

    [HttpPost]
    [ValidateAntiForgeryToken] //<--- This is important
    public async Task<IActionResult> StartWorkflow(IEnumerable<WorkflowModel> model)
    

    C #에서 및 모델 :

    public class WorkflowModel
     {
            public int OrderId { get; set; }
            public int OrderLineId { get; set; }
            public bool IsCustomOrderLine { get; set; }
            public string FolderPath { get; set; }
            public string FileName { get; set; }
     }
    

    결론:

    오류의 원인 :

    "Failed to load resource: the server responded with a status of 400 (Bad Request)"
    

    가 속성 : [ValidateAntiForgeryToken]를 MVC 액션 StartWorkflow에 대한

    Ajax 호출에 솔루션 :

      beforeSend: function (xhr) {//<--- This is important
                          xhr.setRequestHeader("RequestVerificationToken",
                          $('input:hidden[name="__RequestVerificationToken"]').val());
                        },
    

    이 예에서 (목록 개체 채우기)와 같은 데이터를 형성해야 할 객체의 목록을 보내려면 :

    데이터 : {모델 : 목록}

    입력 : "게시물"


  13. 13.이것은 나에게 벌금을 작동하는 방법이다 :

    이것은 나에게 벌금을 작동하는 방법이다 :

    var things = [
        { id: 1, color: 'yellow' },
        { id: 2, color: 'blue' },
        { id: 3, color: 'red' }
    ];
    
    $.ajax({
        ContentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '/Controller/action',
        data: { "things": things },
        success: function () {
            $('#result').html('"PassThings()" successfully called.');
        },
        error: function (response) {
            $('#result').html(response);
        }
    });
    

    자본 "C"에서 "ContentType을"로.

  14. from https://stackoverflow.com/questions/13242414/passing-a-list-of-objects-into-an-mvc-controller-method-using-jquery-ajax by cc-by-sa and MIT license