mvc5 ajax post json,Ajax json to MVC5 controller: Passing object conta

Folks, I've attempted this on MVC4 and MVC5.

I need to pass an object with a few properties and a collection from the client to the controller.

I've defined the model in C# as:

public enum RequestMode { ReadOnly = 0, Edit = 1}

public class DataRequest

{

public int ProjectId { get; set; }

public RequestMode Mode { get; set; }

public List PageRequests { get; set; }

public DataRequest()

{

PageRequests = new List();

}

}

public class PageRequest

{

public int Id { get; set; }

public int PageCurrent { get; set; }

public int RowCountPerPage { get; set; }

}

The MVC Controller is defined as (just using it to set a breakpoint to check the request values):

[HttpPost]

public JsonResult Test(DataRequest request)

{

return new JsonResult();

}

The Index.cshtml client contains the ajax call:

var RequestMode = { ReadOnly: 0, Edit: 1 };

var dataRequest = { ProjectId: 17, Mode: RequestMode.Edit, PageRequests: new Array() };

var pageRequest = { TableId: 3165, PageCurrent: 4, RowCountPerPage: 30 };

dataRequest.PageRequests.push(pageRequest);

$(document).ready(function () {

$.ajax({

data: dataRequest,

type: 'POST',

cache: false,

url: '/Home/Test',

success: function (data) {

},

fail: function (data) {

}

});

});

I start debugging, the page loads and my breakpoint in the controller Test method gets hit.

In the debugger, the request object shows up as:

Mode: Edit

PageRequests: Count = 1

ProjectId: 17

When I expand the PageRequests collection property, I see:

{Mvc5WebTest.Controllers.PageRequest}

Id: 0

PageCurrent: 0

RowsPerPage: 0

I would expect the PageRequest object to be populated with the values I've set (i.e. 3165, 4, 30)

Using Fiddler, I see that the complete DataRequest object is getting turned into Json correctly, but it seems that the MVC controller can't turn it back into the C# object.

As a workaround, I can modify the ajax call on the client to

var cdr = JSON.stringify(dataRequest);

$.ajax({

dataType: 'json',

type: 'GET',

data: { jsonRequest: cdr },

...

And then in the controller

[HttpGet]

public ActionResult Test(string jsonRequest)

{

var request = JsonConvert.DeserializeObject(jsonRequest);

return new JsonResult();

}

This works, but I'd rather not pass the data as a string.

Can anyone shed some light as to what is going on and what I need to do to get the collection populated?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值