加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.NET MVC – 结合Json结果与ViewResult

发布时间:2020-12-15 19:05:42 所属栏目:asp.Net 来源:网络整理
导读:我可以返回一个包含渲染视图的Json结果吗? 我需要它返回一个提交的表单的新ID以及其HTML和一些其他属性。 另外,当我需要从一个Json对象中的一个动作返回两个(或更多)视图结果时,这也是有帮助的。 谢谢! 解决方法 您还可以将一个PartialViewResult渲染为
我可以返回一个包含渲染视图的Json结果吗?

我需要它返回一个提交的表单的新ID以及其HTML和一些其他属性。

另外,当我需要从一个Json对象中的一个动作返回两个(或更多)视图结果时,这也是有帮助的。

谢谢!

解决方法

您还可以将一个PartialViewResult渲染为字符串,然后将此字符串通过JSON传递到您的视图,使用jQuery在您的页面中呈现它。

你可以看到在这篇文章:http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/。

我创建了一个扩展,使其更容易:

public static class MvcHelpers
{
    public static string RenderPartialView(this Controller controller,string viewName,object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

        controller.ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext,viewName);
            var viewContext = new ViewContext(controller.ControllerContext,viewResult.View,controller.ViewData,controller.TempData,sw);
            viewResult.View.Render(viewContext,sw);

            return sw.GetStringBuilder().ToString();
        }
    }
}

在我的控制器中,我叫它如下:

const string msg = "Item succesfully updated!";
return new JsonResult
           {
               Data = new
                          {
                              success = true,message = msg,view = this.RenderPartialView("ProductItemForm",model)
                          },JsonRequestBehavior = JsonRequestBehavior.AllowGet
           };

其中“this”是控制器的情况下,“ProductItemForm”是我的视图和“模型”是我的productItem对象:)

希望这可以帮助

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读