ASP.NET MVC - 将 Json 结果与 ViewResult 结合

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1181849/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:17:43  来源:igfitidea点击:

ASP.NET MVC - Combine Json result with ViewResult

asp.net-mvcjsonpartial-views

提问by elado

Can I return a Json result that contains also a rendered view?

我可以返回一个包含渲染视图的 Json 结果吗?

I need it to return the new ID of a submitted form along with its HTML and some other properties.

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

Also that can be helpful when I need to return two (or more) view results from one action inside a Json object.

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

Thanks!

谢谢!

回答by Diego Ponciano

You can also render a PartialViewResult to a string, and then pass this string via JSON to your view, rendering it in your page using jQuery.

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

You can see that in this post: http://www.atlanticbt.com/blog/asp-net-mvc-using-ajax-json-and-partialviews/.

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

I've created an extension to make it easier:

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

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();
        }
    }
}

In my controller I call it as follows:

在我的控制器中,我这样称呼它:

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

Where "this" is the controller in the case, "ProductItemForm" is my view and "model" is my productItem object :)

在这种情况下,“this”是控制器,“ProductItemForm”是我的视图,“model”是我的 productItem 对象:)

Hope this helps ;)

希望这可以帮助 ;)

回答by Jason Capriotti

I've been thinking about this problem for a while. My solution is similar to returning the partial view HTML as a JSON string, but the opposite. Return a partial view with JSON embedded in it. I did not like this approach until jQuery 1.4.3 merged their .data() method with the HTML 5 data attribute. This makes it much easier to generate JSON within a ASP.NET MVC view, and read it via jQuery.

我一直在思考这个问题。我的解决方案类似于将部分视图 HTML 作为 JSON 字符串返回,但相反。返回嵌入了 JSON 的部分视图。我不喜欢这种方法,直到 jQuery 1.4.3 将他们的 .data() 方法与 HTML 5 数据属性合并。这使得在 ASP.NET MVC 视图中生成 JSON 并通过 jQuery 读取它变得更加容易。

See example... It isn't perfect, but I like it much better than creating hidden form inputs or helpers that render the partial view before returning it.

请参阅示例...它并不完美,但我喜欢它比创建隐藏的表单输入或在返回之前呈现局部视图的助手要好得多。

Partial View:

部分视图:

<div id="content">
  <h1>Some Title</h1>
  <p>Ipsum Lorem</p>
</div>
<div id="dataDiv" data-stuff='{ "name": "Jason", "color": "Blue"}'></div>

JavaScript that reads the JSON

读取 JSON 的 JavaScript

$(document).ready(function () {
  var name = $('#dataDiv').data('stuff').name;
  var color = $('#dataDiv').data('stuff').color;
  alert(name + ' ' + color);
});

This may appear to go against the "single responsibility principle" (if you apply it to views). However, if your application requires both pieces of data to be transmitted in a response, then I see nothing wrong with it. And as long as your model is constructed properly, it won't go against any design principles.

这似乎违反了“单一责任原则”(如果您将其应用于视图)。但是,如果您的应用程序需要在响应中传输这两条数据,那么我认为它没有任何问题。只要您的模型构造正确,它就不会违背任何设计原则。

回答by tvanfosson

In the first case, I think you can just return HTML, but embed the data in the returned form. Use jQuery to access the data in your success callback.

在第一种情况下,我认为您可以只返回 HTML,但将数据嵌入返回的表单中。使用 jQuery 访问成功回调中的数据。

$.ajax({
    url: '<%= Url.Action( "MyAction" )',
    dataType: 'html',
    data: $('form').serialize(),
    success: function(data) {
                $('form').html(data);
                var id = $('form').find('input#formId[type=hidden]').val();
             }
});

In the second case, a shared View that takes two or more ViewNames and uses RenderPartial is probably a better solution that returning HTML through JSON.

在第二种情况下,采用两个或多个 ViewName 并使用 RenderPartial 的共享视图可能是通过 JSON 返回 HTML 的更好解决方案。

Multiview.aspx

多视图.aspx

 ...
<% foreach (string viewName in Model.Views)
   {
       Html.RenderPartial( viewName );
   }
%>

Then in your action:

然后在你的行动中:

public ActionResult MyAction(...)
{
     ... set up model with data
     model.Views = new List<string> { "View1", "View2" };

     return View( "Multiview", model );
}

回答by paracycle

This might be a little hacky (and I am writing of the top of my head) but you might want to create your own subclass of ActionResult and also implement a ResultFilter which would intercept these specific types of ActionResult and render the relevant Views and fill a JsonResult and return it.

这可能有点 hacky(我正在写我的头顶)但您可能想要创建自己的 ActionResult 子类并实现一个 ResultFilter 它将拦截这些特定类型的 ActionResult 并呈现相关视图并填充JsonResult 并返回它。

For example you can define:

例如,您可以定义:

public CompoundResult: ActionResult
{
    public string ViewName { get; set; }
    public JsonResult JsonResult { get; set; }
    public CompoundResult(string viewName, JsonResult jsonResult)
    {
       ViewName = viewName;
       JsonResult = jsonResult;
    }
}

and then in a ResultFilter, render the relevant view and merge it into the relevant place in the JsonResult and finally return the JsonResult to the client.

然后在一个 ResultFilter 中,渲染相关视图并合并到 JsonResult 中的相关位置,最后将 JsonResult 返回给客户端。

Apart from all of this, you might want to change your approach in how you do this, eg. you might try returning a full view (ie HTML) from your action a part of which is the view you want to return but which also includes some extra information that would have otherwise been in your JSON object. You can take out the relevant components from the returned HTML using simple jQuery operations on the client-side.

除此之外,您可能希望改变您的做法,例如。您可能会尝试从您的操作中返回一个完整视图(即 HTML),其中一部分是您想要返回的视图,但其中还包括一些原本会出现在您的 JSON 对象中的额外信息。您可以在客户端使用简单的 jQuery 操作从返回的 HTML 中取出相关组件。