是否可以将动作的结果转换为字符串变量
我需要这样的东西:
public ActionResult Do()
{
var s = this.Index().GetStringResult();
...
}
答案 0 :(得分:2)
Omu - 试试这些尺寸:
public static class ExtensionMethods
{
// usage
/*
var model = _repository.Find(x => x.PropertyID > 3).FirstOrDefault();
var test = this.RenderViewToString("DataModel", model);
return Content(test);
*/
public static string RenderViewToString<T>(this ControllerBase controller,
string viewName, T model)
{
using (var writer = new StringWriter())
{
ViewEngineResult result = ViewEngines
.Engines
.FindView(controller.ControllerContext,
viewName, null);
var viewPath = ((WebFormView)result.View).ViewPath;
var view = new WebFormView(viewPath);
var vdd = new ViewDataDictionary<T>(model);
var viewCxt = new ViewContext(
controller.ControllerContext,
view,
vdd,
new TempDataDictionary(), writer);
viewCxt.View.Render(viewCxt, writer);
return writer.ToString();
}
}
public static string RenderPartialToString<T>(
this ControllerBase controller,
string partialName, T model)
{
var vd = new ViewDataDictionary(controller.ViewData);
var vp = new ViewPage
{
ViewData = vd,
ViewContext = new ViewContext(),
Url = new UrlHelper(controller.ControllerContext.RequestContext)
};
ViewEngineResult result = ViewEngines
.Engines
.FindPartialView(
controller.ControllerContext,
partialName);
if (result.View == null)
{
throw new InvalidOperationException(
string.Format("The partial view '{0}' could not be found",
partialName));
}
var partialPath = ((WebFormView)result.View).ViewPath;
vp.ViewData.Model = model;
Control control = vp.LoadControl(partialPath);
vp.Controls.Add(control);
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
{
using (var tw = new HtmlTextWriter(sw))
{
vp.RenderControl(tw);
}
}
return sb.ToString();
}
}
用法(普通视图):
var s = this.RenderViewToString("Index", null); // or model if required
和部分:
var s = this.RenderPartialToString("PartialView, model) // etc
答案 1 :(得分:0)
为什么不采取Index操作并将其所有代码提取到一个单独的函数中,如下所示:
public ActionResult Index()
{
Response.Write(GetActionString());
return new EmptyResult();
}
private void GetActionString()
{
//Code which produces the index string;
}
public ActionResult Do()
{
var s = GetActionString();
...
return View();
}
如果在传递给视图后需要从索引中呈现HTML,那么您需要在代码中创建一个HttpRequest并从中读取结果。