1

I have two controller actions, where one is used to return the view in a standard way and another returns a large chunk of the same view for use in, for example, a javascript modal somewhere else in my application. My question is what would be the best practise way to do this, or if the way I have done it is ok. Maybe I should move the duplicated code out to a helper method?

(Note the Create View has the _Create partial inside it)

Right now I have:

public ActionResult Create(int someParamater)
{
    //Lots of code 
    return View(model);
}

public PartialViewResult GetCreatePartial(int someParameter)
{
    //All of the same code as in Create
     return PartialView("_Create", model);
}

2 Answers 2

1

You can check on some condition and return PartialView or View on its basis, instead of creating a separate action:

public ActionResult Create(int someParamater)
{
    if(Request.IsAjaxRequest())   // check here if ajax call return partial
       return PartialView("_Create", model);
    else
       return View(model); // otherwise return Full View
}
Sign up to request clarification or add additional context in comments.

2 Comments

somecondition could probably be Request.IsAjaxRequest()
With @Haim770's comment that makes a lot of sense. I'll have a go at implementing that and see how it goes...
1

If indeed your GetCreatePartial method can be called standalone, and the someParameter argument is available in the View as well, you can call it within parent view using Html.Action().

For example (Create.cshtml):

<div>
    <span>some parent view stuff</span>
</div>

<div class="partial-wrapper">
    @Html.Action("GetCreatePartial", new { someParameter = Model.someParameter })
</div>

See Html.Action

3 Comments

My question was more about how to structure the controller in the best way
It should affect the way you're structuring the Controller as well as there's no need to fetch the model for the partial. In many cases it means that your Create method would only return View(someParamater);. Hard to provide full example when not enough code provided, but the core idea is that you can execute GetCreatePartial method (not as some partial rendering) from within parent view.
Understood, and that does make sense. Definitely valid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.