定义输入参数的名称

时间:2013-12-23 17:40:56

标签: jquery html ajax asp.net-mvc-3 asp.net-mvc-4

我正在通过AJAX向JQuery提交一些数据(Collection<Cars>),但现在我不知道如何在Action输入参数中定义对象。我已经尝试定义为 FormCollection ,我收到了所有数据。但是我真正想要的是定义为 ICollection<Car> ,但是当我这样做时,我的对象变为空。我怎样才能做到这一点?或者我如何将FormCollection 解析为ICollection<Car>

我的控制器:

public ActionResult UpdateTable(ICollection<Car> collection)
{
//some code
}

我的js:

function updateTable(tableId) {
        if (tableId == "myTable") 
        {
            event.preventDefault();

            if ($("#" + tableId + " tbody tr").length % 2 == 0)

                var myTableData = $("#" + tableId).find("select, input").serializeObject();

            $.post("../../Car/UpdateTable/", myTableData , function(partial) {
                $("#myOtherTable tbody").append(partial);
            });
        }
    }

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

Car.cs:

public int Id { get; set; }
public string Name { get; set; }
public ICollection<Owner> Owners { get; set; }
public bool IsSold { get; set; }

结果:

当输入参数为ICollection<Car>时,操作控制器会出现什么: null

当输入参数为FormCollection时(在AllKeys中),操作控制器会出现什么:

Car[0].Id
Car[0].Name
Car[0].Owners
IsSold

我的观点(行表):

    <tr>
        <td>
            @Html.TextBoxFor(model => model.Id, new { Name = modelFieldInitialName + "Id", id = modelFieldInitialId + "Id" })
            @Html.ValidationMessageFor(model => model.Id)
        </td>
        <td>
            @Html.TextBoxFor(model => model.Name, new { Name = modelFieldInitialName + "Name", id = modelFieldInitialId + "Name" })
            @Html.ValidationMessageFor(model => model.Name)
        </td>
        <td>
            @Html.DropDownListFor(model => model.Owners, new SelectList(TempData["OwnersList"] as IEnumerable, "Id", "Description"), "", new { Name = modelFieldInitialName + "Owners", id = modelFieldInitialId + "Owners" })
            @Html.ValidationMessageFor(model => model.Owners)
        </td>
        <td>
            @Html.CheckBoxFor(model => model.IsSold, new { type = "checkbox", Name = modelFieldInitialName + "IsSold", id = modelFieldInitialId + "IsSold" })
            @Html.ValidationMessageFor(model => model.IsSold)
        </td>
   </tr>

2 个答案:

答案 0 :(得分:0)

几天前我遇到了类似的情况我发布了我的解决方案。

我假设你的表看起来像这样。

<table id="partTable">
<tr>
    <td class="cell">Nitin</td>
    <td class="desc">Varpe</td>
    <td class="desc">8881</td>
</tr>
<tr>
    <td class="cell">Parag</td>
    <td class="desc">Lombar</td>
    <td class="desc">4999</td>
</tr>

</table>
<div>
<input type="button" id="sendRequest" value="send" />
</div>

<script type="text/javascript">

    $('#sendRequest').click(function (e) {
        PostTable();
    });


    // Read a row
    function GetRow(rowNum) {
        var tableRow = $('#partTable tr').eq(rowNum);

        var row = {};

        row.FirstName = tableRow.find('td:eq(0)').text();
        row.LastName = tableRow.find('td:eq(1)').text();
        row.RollNumber = tableRow.find('td:eq(2)').text();


        return row;
    }

    // Read all rows
    function GetAllRows() {
        var dataRows = [];

        $('#partTable tr').each(function (index, value) {
            var currentRow = GetRow(index);
            dataRows.push(currentRow);
        });

        return dataRows;
    }

    // POST rows to server
    function PostTable() {
        //var crossId = getParameterByName('id');
        var jsonRequest = { rows: GetAllRows()};

        $.ajax({
            type: 'POST',
            url: "@(Url.Action("Action", "Controller"))",
            data: JSON.stringify(jsonRequest),
           contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            async: false,
            success: function (data) {
            //ur logic after success                
              return true;
            },
            error:function (ts){
            alert(ts.responseText);
                return false;
                }

                });
            } 

    </script>

这是班级。

public class Row
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string RollNumber { get; set; }

    }

致电

的行动
public ActionResult GetRows(List<Row> rows)
        {
           //your logic

            return Json(new
            {
                list = object
            });

        }

希望这有帮助!

答案 1 :(得分:0)

好的,经过深思熟虑并尝试我的代码,我终于发现了问题:

如果我们向视图发送包含CarStand的模型类型ICollection<Car>(例如),在这样的情况下我们构建一个动态表(并定义元素名称和ID) ),为了接收与FormCollection不同的内容,我们不能指望控制器收到ICollection<Car>

传递给视图的模型( CarStand.cs ):

public ICollection<Car> Cars{ get; set; }
//other properties

但是我们可以向控制器发送/发布传递给视图的整个模型,但是我们需要选择的数据。所以,它是这样做的:

public ActionResult UpdateTable(CarStand collection)
{
//some code
}

JQuery可以保持原样:

function updateTable(tableId) {
        if (tableId == "myTable") 
        {
            event.preventDefault();

            if ($("#" + tableId + " tbody tr").length % 2 == 0)

                var myTableData = $("#" + tableId).find("select, input").serializeObject();

            $.post("../../Car/UpdateTable/", myTableData , function(partial) {
                $("#myOtherTable tbody").append(partial);
            });
        }
    }