Return HTML from action / model

本文关键字:model action from HTML Return | 更新日期: 2023-09-27 18:15:57

是否有任何方法可以向Action和Model组合发出GET请求以返回HTML,而不是向URI发出GET请求?

通常在我的代码中我会写

 return View("myView", myModel);

我想从中返回HTML,并能够读取HTML。

类似于:

 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

Return HTML from action / model

这里有可用的东西,您可以将模型作为参数传递。虽然仍然不确定你为什么要这样做…可在github上获得备用源代码。

无论如何,如果你只想以某种方式改变HTML,另一个选择是重定向到视图,然后使用一个动作过滤器,在那里你可以做任何你可能需要的后处理。

这所做的是渲染任何视图到HTML,并返回作为String。虽然是一个更大的类的一部分,但相关部分如下(Context实际上是Controller.ControllerContext):

/// <summary>
/// Internal method that handles rendering of either partial or 
/// or full views.
/// </summary>
/// <param name="viewPath">
/// The path to the view to render. Either in same controller, shared by 
/// name or as fully qualified ~/ path including extension
/// </param>
/// <param name="model">Model to render the view with</param>
/// <param name="partial">Determines whether to render a full or partial view</param>
/// <returns>String of the rendered view</returns>
protected string RenderViewToStringInternal(string viewPath, object model,
                                            bool partial = false)
{
    // first find the ViewEngine for this view
    ViewEngineResult viewEngineResult = null;
    if (partial)
        viewEngineResult = ViewEngines.Engines.FindPartialView(Context, viewPath);
    else
        viewEngineResult = ViewEngines.Engines.FindView(Context, viewPath, null);
    if (viewEngineResult == null)
        throw new FileNotFoundException(Resources.ViewCouldNotBeFound);
    // get the view and attach the model to view data
    var view = viewEngineResult.View;
    Context.Controller.ViewData.Model = model;
    string result = null;
    using (var sw = new StringWriter())
    {
        var ctx = new ViewContext(Context, view,
                                    Context.Controller.ViewData,
                                    Context.Controller.TempData,
                                    sw);
        view.Render(ctx, sw);
        result = sw.ToString();
    }
    return result;
}