截止上篇文章asp.net mvc源码分析-ActionResult篇 RazorView.RenderView 相信大家对mvc的大致流程应该有所了解。现在我们来看看我们在mvc开发中用的最多的几个方法,我想排在第一的应该是Html.RenderAction和Html.RenderPartial吧。先说简单的吧:RenderPartial和Partial
public static void RenderPartial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData) {
htmlHelper.RenderPartialInternal(partialViewName, viewData, model,htmlHelper.ViewContext.Writer, ViewEngines.Engines);
}
public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName, object model, ViewDataDictionary viewData) {
using (StringWriter writer = new StringWriter(CultureInfo.CurrentCulture)) {
htmlHelper.RenderPartialInternal(partialViewName, viewData, model,writer, ViewEngines.Engines);
return MvcHtmlString.Create(writer.ToString());
}
}
从这里我们可以知道RenderPartial和Partial它们返回的东西写到的流不一致,一个是当前的writer,一个是新建的writer,当然新建的writer便于返回字符文本。
internal virtual void RenderPartialInternal(string partialViewName, ViewDataDictionary viewData, object model, TextWriter writer, ViewEngineCollection viewEngineCollection) {
if (String.IsNullOrEmpty(partialViewName)) {
throw new ArgumentException(MvcResources.Common_NullOrEmpty, "partialViewName");
}
ViewDataDictionary newViewData = null;
if (model == null) {
if (viewData == null) {
newViewData = new ViewDataDictionary(ViewData);
}
else {
newViewData = new ViewDataDictionary(viewData);
}
}
else {
if (viewData == null) {
newViewData = new ViewDataDictionary(model);
}
else {
newViewData = new ViewDataDictionary(viewData) { Model = model };
}
}
ViewContext newViewContext = new ViewContext(ViewContext, ViewContext.View, newViewData, ViewContext.TempData, writer);
IView view = FindPartialView(newViewContext, partialViewName, viewEngineCollection);
view.Render(newViewContext, writer);
}
看看 是不是很简单,而这里的FindPartialView其实核心代码就一句,
ViewEngineResult result = viewEngineCollection.FindPartialView(viewContext, partialViewName);我们从前面的文章中知道FindView 和FindPartialView的逻辑是一致的。
现在 我们来看看RenderAction和