RenderAction calls the wrong action method

I am struggling with rendering, the problem is that it calls the wrong action method on my controller.

My Users controller has two action methods called edit: one for get and one for post-requests:

public virtual ActionResult Edit(int id) { //return a view for editing the user } [AcceptVerbs(HttpVerbs.Post)] public virtual ActionResult Edit(UserViewModel model) { //modify the user... } 

In my opinion, I call Renderaction as follows:

 Html.RenderAction("Edit", "Users", new { id = 666}); 

Now the problem is that I want the GET action method to display. However (perhaps because the model also contains a property called ID?), Renderaction instead calls my POST action method.

What is the right way to do this? I use ASP.NET MVC 3 RC, if that matters.

Thanks,

Adrian

+6
asp.net-mvc asp.net-mvc-3 renderaction
source share
4 answers

The subtitle uses the HTTP method of its parent action.

The problem is that your view is displayed after the postback action. All sub-action views in the view use the same HTTP method. Thus, the POST is replicated to them. I'm not sure about MVC3, but in MVC2 there was no built-in way to overcome this problem.

So the problem is that you want your Edit() action to display as GET on the POST view. Out of the box. In no case.

You can, of course, do this by providing your own functionality = classes.

+12
source share

This does not even compile:

 public virtual ActionResult Edit(UserViewModel model) {} [AcceptVerbs(HttpVerbs.Post)] public virtual ActionResult Edit(UserViewModel model) {} 

You cannot have two methods with the same name and the same arguments in the same class. Also why are your actions virtual ?


UPDATE:

Unable to play. This does not seem to be the case:

 public class UserViewModel { public int Id { get; set; } } public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult Edit(int id) { return View(new UserViewModel()); } [HttpPost] public ActionResult Edit(UserViewModel model) { return View(model); } } 

And in Index.cshtml visualize the editing action calls the correct Edit action (one with the id parameter):

 @{Html.RenderAction("edit", "home", new { id = "123" });} 
+2
source share

I am not 100% sure if this is available in MVC3, but in MVC2 (with MvcFutures: Microsoft.Web.MVC) I would use:

 Html.RenderAction<UsersController>(c => c.Edit(666)); 
0
source share

I know this is very old, and we are now on MVC5, but this is still the behavior shown when running Html.RenderAction() .

My solution for this particular case was to do a check of my [HttpPost] action for the values ​​in my view model, and if they were null (or something else), I called my return Edit() , and if they didn't were I called AntiForgery.Validate() to validate the token correctly.

0
source share

All Articles