4
votes

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.

1

1 Answers

4
votes
  1. 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 :

enter image description here

  1. However , it is not recommended to put partial view logic in PageModel . Using it in the Page file as below is much nicer:

@if(){
    <partial name="" />
}else{
    <partial name="" /> 
}