如何在常规控制器方法(从客户端调用)中更新视图?

时间:2012-04-11 19:29:42

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

如何在控制器中定义的标准方法中更新视图?该方法是从我连接的jquery插件调用的。

查看:

    @model ViewModel

    @Html.EditorFor(model => model.First)
    @Html.EditorFor(model => model.Last)

    @Html.EditorFor(model => model.Junk)

控制器方法:

    // Called from third party jquery plugin
    public string DoSomeWorkAndUpdateMyView(string Id)
    {
        // Get persisted View from dbcontext...
        // Create a new Junk object with the new id and add it to the db context
        // Update the view with the newly added junk object
        ViewModel model = dbContext.GetViewStuff();
        model.Junk.Add(new junk);

        return View("JunkView", model);
    }

用法:

   ...
   onComplete: function (event, queueID, fileObj, response, data) 
                {
                    $.ajax(
                { url: '@Url.Action("ProcessForm","Home")',
                    data: { first: $("#fname").val() },
                    success: function (data) {
                        $("#fname").val(data);
                    }
                })
                }
   ...

1 个答案:

答案 0 :(得分:1)

我认为没有一种简单的方法可以在Ajax调用中返回模型,并以您考虑的方式更新View。所以你可以定期进行POST / GET,或者做一些工作:

    public JsonResult DoSomeWorkAndUpdateMyView(string Id)
    {
        Dictionary<string, string> result = new Dictionary<string, string>();

        if (DoSomeWork())
        {
            result.Add( "status", "success" );
            result.Add( "id", Id ); // any info the client will need to reload the page
        }
        else
        {
            result.Add("status", "error");
            result.Add( "error", "Some Error Message"); 
        }

        return Json(result);
    }

然后在接收端检查响应状态。如果“成功”,则使用document.location=重新加载整个页面。

如果您必须在一个电话中执行此操作,则需要执行类似

的操作
return Json(model);

然后手动设置客户端上每个元素的值。