将JSON数据绑定回MVC视图以动态地将数据插入表中

时间:2013-10-16 15:03:01

标签: asp.net-mvc-4

我正在研究MVC4应用程序。在按钮的提交操作中,我正在调用一个控制器动作,它会将数据作为Json返回给我。表中的行数取决于服务返回的行数。

我创建了一个新的View模型来支持这个。

public class DataResponse
{
    public List<ALSResult> Result { get; set; }
    public string ResponseText {get;set;}
}
public class ALSResult
{
    public string Name {get;set;}
    public string DataResult {get;set;}
}

控制器操作

[HttpPost]
public ActionResult Submit(CViewModel calcModel)
{
    try
    {
        DataResponse response = cRepository.GetDetails(calcModel.SelectedPlan,calcModel.EquipmentPrice,calcModel.DownPayment);
        return Json(response, JsonRequestBehavior.DenyGet);
    }
}

js file

$("#Submit").click(function () {
    other code here
    Process("/DPPC/Submit", "POST", JSON.stringify(model), "json", "application/json;charset=utf-8", logError, InvokeSuccess);
}

function InvokeSuccess(result) {
    i will get json result in result filed
}

index.cshtml

<table id="tblResults">
    <tr>
         <td id="tdResultEt"></td>
         <td id="tdResultEtPrice"></td>
    </tr>
    <tr>
         <td id="tdResultDt"></td>
         <td id="tdResultDtPrice"></td>
    </tr>
    more rows depending on the number of items in the JSON response
</table>

如何动态绑定服务的响应以创建表的行并绑定结果?

1 个答案:

答案 0 :(得分:0)

我没有测试它,它可能包含语法错误

function InvokeSuccess(result) {

    var table = $("#tblResults");
    for(var i = 0; i < result.Result.lenght; ++i)
    {
        var item = result.Result[i];
        var newTr = $("<tr>");
        var newTd1 = $("<td>");
        var newTd2 = $("<td>");

        newTd1.text(item.Name);
        newTd2.text(item.DataResult);

        newTr.append(newTd1);
        newTr.append(newTd2);

        table.append(newTr);
    }
}