如何从ajax调用中检索来自一个控制器的viewmodel数据

时间:2017-06-15 21:40:55

标签: javascript c# ajax asp.net-mvc

我有一个调用控制器中的方法的ajax调用,我将数据分配给我希望能够在视图上读出的视图模型。在控制器方法完成后,我无法将更新的视图模型传递给视图。

的Javascript

$ANALYZE = $('#submitID');

$ANALYZE.click(function () {
    var objectID = document.getElementById('objectIDInput').value;

    $.ajax({
        url: '@Url.Action("AnalyzeData")',
        type: "POST",
        dataType: "json",
        data: { 'objectID': objectID },
        success: function (response) {
            alert(response.responseText);
        },
        error: function (response) {
            alert(response.responseText);
        }
    });
});

控制器

public ActionResult Index(AnalyzeViewModel data)
{
    //Display table to view
    AnalyzeViewModel avm = new AnalyzeViewModel();
    if (data != null)
        avm.fileData = data.fileData;
    else
        avm.fileData = null;

    return View(avm);
}

[HttpPost]
public ActionResult AnalyzeData (int objectID)
{
    List<string> retList = new List<string>();
    AnalyzeViewModel avm = new AnalyzeViewModel();

    try {
        retList = SOME LIST

        avm.fileData = retList.ToArray();

        Response.StatusCode = (int)HttpStatusCode.OK;
        var obj = new
        {
            success = true,
            responseText = "Zones data has been calculated."
        };
        return Json(obj, JsonRequestBehavior.AllowGet);
    }

查看

<tbody class="scrollContent">
    @if (Model.fileData != null)
    {
        foreach (string line in Model.fileData)
        {
            @Html.Raw(line);
        }
    }
</tbody>

1 个答案:

答案 0 :(得分:0)

您好,您可以编写如下代码,以获取jquery成功功能中的数据

<强> Jquery的

$ANALYZE = $('#submitID');

    $ANALYZE.click(function () {
        var objectID = document.getElementById('objectIDInput').value;

        $.ajax({
            url: '@Url.Action("AnalyzeData")',
            type: "POST",
            dataType: "json",
            data: { 'objectID': objectID },
            success: function (data) {
               //data here refers the viewmodel
              // some logic
            },
            error: function (response) {
                alert(response.responseText);
            }
        });
    });

控制器方法代码:

[HttpPost]
public ActionResult AnalyzeData (int objectID)
{
    List<string> retList = new List<string>();
    AnalyzeViewModel avm = new AnalyzeViewModel();

    try {
        retList = SOME LIST

        avm.fileData = retList.ToArray();

        Response.StatusCode = (int)HttpStatusCode.OK;
        var obj = new
        {
            success = true,
            responseText = "Zones data has been calculated."
        };


        return Json(avm, JsonRequestBehavior.AllowGet);
    }

希望它有用

由于

KARTHIK