Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send model object in Html.RenderAction (MVC3)

Tags:

I'm using MVC3 razor, and I'm trying to pass an object to a partial view, and it's not working.

This works fine without sending the object model to the partial view:

Html.RenderAction("Index", "ViewName"); 

Trying this doesn't sent the model object, i'm getting nulls instead (the object has data, and the view expects it):'

Html.RenderAction("Index", "ViewName", objectModel); 

Is this even possible using RenderAction?

Thanks!

Edit: I found the error, there was an error with the controller's action that didn't pick up the sent object. Thanks for all your help!

like image 259
Michael Avatar asked Jan 22 '12 06:01

Michael


People also ask

What is RenderAction in MVC?

RenderAction(HtmlHelper, String) Invokes the specified child action method and renders the result inline in the parent view. RenderAction(HtmlHelper, String, Object) Invokes the specified child action method using the specified parameters and renders the result inline in the parent view.

What is the difference between HTML action and HTML RenderAction?

The difference between the two is that Html. RenderAction will render the result directly to the Response (which is more efficient if the action returns a large amount of HTML) whereas Html. Action returns a string with the result.


2 Answers

You can actually pass an object to a controller method using Action. This can be done on any avaialble view, for instance I have one in a shared library that gets built to project bin folders that reference my shared project (properties - Copy if newer on the view file, in Visual Studio). It is done like so:

Controller:

public class GroovyController : Controller {     public ActionResult MyTestView(MyModel m)     {         var viewPath = @"~\bin\CommonViews\MyTestView";         return View(viewPath, m);     } } 

MVC page (using Razor syntax):

@Html.Action("MyTestView", "Groovy", new { m = Model }) 

or using RenderAction method:

@{ Html.RenderAction("MyTestAction", "MyTestController", new { area = "area", m = Model }); } 

Note: in the @Html.Action(), the Model object must be of type MyModel and that 3rd parameter must be set to the controller variable name, of which mine is MyModel m. The m is what you must assign to, so I do m = Model.

like image 113
theJerm Avatar answered Oct 23 '22 04:10

theJerm


say you want to pass foo as model, make it first

public class Foo {     public string Name { get; set; }     public int Age { get; set; } } 

now make an ActionResult

public ActionResult FooBar(Foo _foo){     return PartialView(_foo); } 

call it

@Html.RenderAction("FooBar", "Controller", new { Name = "John", Age=20 }); 
like image 35
John x Avatar answered Oct 23 '22 05:10

John x