简体   繁体   中英

Model is not attaching with controller in MVC using Ajax call?

I am trying to pass the model from view to controller using ajax AND when I check the value in the JS debugger model has data but it's not binding with controller and the controller model is showing null.

 function BulkUpdate()
       {
           debugger;
           var model = @Html.Raw(Json.Encode(Model.tags))
           $.ajax({
               type: 'GET', //GET
               data: JSON.stringify({model}),
               url: '@Url.Action("BulkUpdate", "Home")',
               contentType: 'application/json; charset=utf-8',
               dataType: "json",
               success: function (data) {
                $('#myModalContent').html(data);
                $('#myModal').modal('show');
               }
           });

        }

//and my controller code is
public ActionResult BulkUpdate(List<Tag> tags)
        {
            ModelAccessor obj1 = new ModelAccessor();
            obj1.updatedDatas = new List<UpdatedData>();
            foreach (var item in tags)
            {
                var tag = db.Tags.Where(x => x.Id.Equals(item.Id)).FirstOrDefault();
                if (tag.TagValue != item.TagValue) 
                {

                   UpdatedData changedRow = new UpdatedData { 
                     OldTagValue=tag.TagValue,
                     NewTagValue=item.TagValue.Trim()
                    };
                    obj1.updatedDatas.Add(changedRow);
                }
            }
            return PartialView("_UpdateConfirmationBulk", obj1);
        }

I have a solution.

function BulkUpdate()
{
   debugger;
   var model = @Html.Raw(Json.Encode(Model.tags))
   $.ajax({
      type: 'GET', //GET
      data: {'tags':JSON.stringify({model})},
      url: '@Url.Action("BulkUpdate", "Home")',
      contentType: 'application/json; charset=utf-8',
      dataType: "json",
      success: function (data) {
      $('#myModalContent').html(data);
      $('#myModal').modal('show');
      }
    });

 }

Try this because your method expects a parameter named tags and this is missing in you ajax call.

Can you try the type by post?

 var model = @Html.Raw(Json.Encode(Model.tags))
       $.ajax({
           type: 'POST', //GET
           data: JSON.stringify({model}),
           url: '@Url.Action("BulkUpdate", "Home")',
           contentType: 'application/json; charset=utf-8',
           dataType: "json",
           success: function (data) {
            $('#myModalContent').html(data);
            $('#myModal').modal('show');
           }
       });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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