This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
PartialViewResult in Controller with ViewData #4294
Comments
You can do that quite easily. Just create the partial view result by yourself public IActionResult Index()
{
var myViewData = new Microsoft.AspNet.Mvc.ViewFeatures.ViewDataDictionary(ViewData);
myViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
myViewData.Model = someModel;
return new PartialViewResult
{
ViewData = myViewData,
ViewName = "MyViewName",
TempData = TempData
};
} And to simplify it, you can create an extension method: public static class ControllerExtensions
{
public static PartialViewResult PartialView(this Controller controller, string viewName, object model, ViewDataDictionary viewData)
{
if (model != null)
{
viewData.Model = model;
}
return new PartialViewResult
{
ViewName = viewName,
ViewData = viewData,
TempData = controller.TempData
};
}
} And then use it like: public IActionResult Index()
{
var myViewData = new Microsoft.AspNet.Mvc.ViewFeatures.ViewDataDictionary(ViewData);
myViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
return this.PartialView("myViewName", someModel, myViewData);
} |
Ah great! Thank you :) Edit: Is there also an easy method to serialize the PartialView afterwards into a String. E.g. in my scenario I want to return the generated view plus some additional information in an JSON object |
ajaybhargavb
added a commit
that referenced
this issue
May 25, 2016
ajaybhargavb
added a commit
that referenced
this issue
May 25, 2016
ajaybhargavb
added a commit
that referenced
this issue
May 25, 2016
Maybe someone will need other variant. public PartialViewResult MyFunction ()
{
ViewData.TemplateInfo.HtmlFieldPrefix = "MyPrefix";
return PartialView("ViewName", MyModel);
} |
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Hi. I have the following scenario: In a View I do an ajax request to a controller, which renders a PartialView based on a posted id.
In the controller I can write
return PartialView("MyView", model);
Now I just have the problem, that in the PartialView, there is a form which is supposed to have a specific prefix. In a View I can use the following:
I think it would be nice, if one could do the same (put a ViewData in the PartialView) in the Controller with that PartialView Result.
The text was updated successfully, but these errors were encountered: