ASP.NET MVC操作无法识别post json数据

时间:2014-07-25 09:31:41

标签: asp.net-mvc json forms model-binding

我有这个表单有3个字段,我想传递给控制器​​操作:

<form role="form" class="form-inline" name="frmUserData" id="frmUserData">
    <div class="form-group">
        <label for="txtlitm">Item Code:</label>
        <input type="text" class="form-control" id="txtlitm" name="txtlitm">
    </div>
    <div class="form-group">
        <label for="txtmcu">Branch Plant (filter):</label>
        <input type="text" class="form-control" id="txtmcu" name="txtmcu">
    </div>
    <div class="form-group">
        <label for="txtlocn">Location (filter):</label>
        <input type="text" class="form-control" id="txtlocn" name='txtlocn'>
    </div>
    <button type="button" class="btn btn-default" id="btnGO">Search</button>
</form>

我的javascript: 版本1:

$.ajax({
    type: "POST",
    data: JSON.stringify($('#frmUserData').serializeArray()),
    contentType: "application/json; charset=utf-8",
    url: action,
    dataType: 'html',
    success: function(data) {
        $(dataContainer).html(data);
        $(what).hide();
    }

版本2:

$.ajax({
    type: "POST",
    data: '{"frmData":' + JSON.stringify($('#frmUserData').serializeArray()) + '}',
    contentType: "application/json; charset=utf-8",
    url: action,
    dataType: 'html',
    success: function(data) {
        $(dataContainer).html(data);
        $(what).hide();
    }

我的MVC行动:

public PartialViewResult GetAvailability(FormModel frmData)
{
    var vm = Bll.GetAvailabilityWithHolds(frmData.txtlitm, frmData.txtmcu, frmData.txtlocn);
    return PartialView(new GetAvailabilityModel{Availability = vm});
}

我的表格类:

public class FormModel
{
    public string txtlitm { get; set; }
    public string txtmcu { get; set; }
    public string txtlocn { get; set; }
}

无论我做什么,我都会在控制器动作中获得空值。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

你试过这个吗?你不需要使用Json,你可以使用标准的表格编码

$.ajax({
type: "POST",
data: $('#frmUserData').serialize(),
url: action,
dataType: 'html',
success: function(data) {
    $(dataContainer).html(data);
    $(what).hide();
}

我无法测试任何这些修复程序,但尝试修复原始解决方案又如何:

尝试1

$.ajax({
    type: "POST",
    data: '{"frmData":' + JSON.stringify($('#frmUserData').serializeArray()[0]) + '}',
    contentType: "application/json; charset=utf-8",
    url: action,
    dataType: 'html',
    success: function(data) {
        $(dataContainer).html(data);
       $(what).hide();
}

尝试2

$.ajax({
    type: "POST",
    data: JSON.stringify($('#frmUserData').serializeArray()[0]),
    contentType: "application/json; charset=utf-8",
    url: action,
    dataType: 'html',
    success: function(data) {
        $(dataContainer).html(data);
        $(what).hide();
}