I am having a problem returning a partial view from a razor page, my scenario is
I have a partial view which is a form and that has a model. I have 3 forms residing on a single razor pages Form A post a ModelA Form B post ModelB My problem is, i want to handle thier specific post event on the parent Page which is a razor page. How would i return this partial view
OnPostModelA(ModelA model)
{
if(! ModelState.IsValid)
return Partialview("_CreateModelA", model);
}
Is this possible using razor pages or this is not possible? I just want to return the partialview with its designated model using ajax.
Rendering Partial PagesThe name attribute takes the name of the partial file without the file extension, or the path of the partial. The value that you provide the name attribute is case-insensitive. The partial tag helper renders the content of the partial asynchronously thereby improving application performance.
How to return a partial view from controller action method? To return a Partial view from the controller action method, we can write return type as PartialViewResult and return using PartialView method.
In ASP.NET Core MVC, a controller's ViewResult is capable of returning either a view or a partial view. In Razor Pages, a PageModel can return a partial view represented as a PartialViewResult object. Referencing and rendering partial views is described in the Reference a partial view section.
As you know ,Razor Pages have no equivalent PartialView
method on the PageModel
. If you do want to invoke different parial views in PageModel
method , simply add a PartialView
Helper Method in you PageModel
:
[NonAction]
public virtual PartialViewResult PartialView(string viewName, object model)
{
ViewData.Model = model;
return new PartialViewResult()
{
ViewName = viewName,
ViewData = ViewData,
TempData = TempData
};
}
Here I use a ViewData.Model
to store your model object , let's say your Model type is named as X1Model
:
you can use it across the partial views .
Create a simple partial view named as _CreateModelA.cshtml
:
@model HelloModel
AAAAA
<div>
@Model.Model.Welcome
</div>
and another partial view named as _CreateModelB.cshtml
:
@model HelloModel
BBBBBBBB
<div>
@Model.Model.Welcome
</div>
At last , you can return PartialView
in your PageModel:
public class HelloModel : PageModel
{
public X1Model Model { get; set; }
public ActionResult OnGet(int rand = 0)
{
var flag = rand % 2 == 0 ? true : false;
var model = new HelloModel() {
Model = new X1Model {
Welcome = "Hello,world",
}
};
if (flag)
{
return PartialView("_CreateModelA", model);
}
else
{
return PartialView("_CreateModelB", model);
}
}
[NonAction]
public virtual PartialViewResult PartialView(string viewName, object model)
{
// ...
}
}
Here's a screenshot :
@if(){
<partial name="" />
}else{
<partial name="" />
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With