【问题标题】:MVC Ajax POST does not bind subobjectMVC Ajax POST 不绑定子对象
【发布时间】:2021-12-21 12:58:04
【问题描述】:

我有一个控制器

 [HttpPost]
 public async Task<IActionResult> Report([FromBody][FromForm] ReportViewModel request)
 {
       var x = request.StartDate; // binds data
       var y = request.Pager.RowsPerPage; // always NULL
}

ReportViewModel 是

public class ReportViewModel : IEntity, IResponse
{
        public string DateRange { get; set; }
        public Pager Pager { get; set; }
}

public class Pager
{
        public int CurrentPage { get; set; }
}

我正在使用 AJAX 调用控制器,这是我从 UI 发送的内容

{"Pager.RowsPerPage":"1","Pager.CurrentPage":"2","StartDate":"2021-11-08T17:25:21.243Z"}

我尝试在 ReportViewModel 构造函数上创建 Pager 对象,但没有成功。

可能是什么问题?

谢谢。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    应该是这样的

    <button id="submitForm">Submit</button>
    
    @section scripts {
    
    <script type="text/javascript">
    
        var formData = '{ "DateRange": "2021/11/08", "Pager": { "CurrentPage": 2 } }';
    
        var options = {
            url: '/Home/Report',
            type: 'POST',
            dataType: 'json',
            data: JSON.parse(formData)
        }
    
        $('#submitForm').click(function () {
    
            $.ajax(options)
            .done(function (response) {
                console.log('response: ', response);
            });
        });
    
    </script>
    
    }
    

    然后在控制器中

        [HttpPost]
        public ActionResult Report(ReportViewModel report)
        {
    
            var dateRange = report.DateRange;
            var page = report.Pager.CurrentPage;
    
            return Json("{ submited = true }", JsonRequestBehavior.AllowGet);
        }
    
    
        public class ReportViewModel
        {
            public string DateRange { get; set; }
            public Pager Pager { get; set; }
        }
    
        public class Pager
        {
            public int CurrentPage { get; set; }
        }
    

    【讨论】:

    • 使用此方法甚至不会绑定主要对象属性。谢谢。
    • 你去吧,我创建了一个小例子并测试了它运行良好的代码。
    • @sairfan 我有一个非常相似的问题。任何帮助,将不胜感激。 stackoverflow.com/questions/69906047/…
    猜你喜欢
    • 1970-01-01
    • 2018-05-29
    • 2017-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多