是有可能得到一個動作的結果爲字符串變量如何獲得字符串的操作(HTML)變量
我需要的是這樣的:
public ActionResult Do()
{
var s = this.Index().GetStringResult();
...
}
是有可能得到一個動作的結果爲字符串變量如何獲得字符串的操作(HTML)變量
我需要的是這樣的:
public ActionResult Do()
{
var s = this.Index().GetStringResult();
...
}
雄武 - 嘗試這些尺寸爲:
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
我們也是這樣做的! – 2010-12-13 10:58:17
是的,對於mvc2來說,這是一種非常乾淨的方式來提取不同的視圖類型。我'幾乎'確定mvc3包含這個'開箱即用'。還沒有嘗試過,但將在2011年:)。季節的問候... – 2010-12-13 11:02:17
爲什麼不走索引行動並提取它的所有的代碼放到一個單獨的函數是這樣的:
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並從中讀取結果。
因爲索引返回View() – Omu 2010-12-13 12:32:58
是的,有一些方法。將粘貼我的mvc2擴展爲此在單獨的職位。 – 2010-12-13 10:50:13
請參閱此答案以將視圖呈現爲字符串:http://stackoverflow.com/q/483091/261677 – 2010-12-13 10:54:19