I am trying to figure out how to pass the model object from controller to view in a following scenario:
<% Html.Action("GetRequest", "The_Controller", new { requestId = 12 }); %>
<% Html.RenderPartial("Request", ViewData.Model); %>
The action should, and it does, call the controller’s method which looks up the Request object in the DB repository and returns a Request object.
The partial view, named Request, should receive the request object and display it.
The problem is that the ViewData.Model is always null?!
I have tried to figure it out, but with no success 🙁
The reason for this behavior is that I need to display a partial view inside the jQuery’s modal dialog based on the requestId value provided by the jQGrid. I have reached the point where I open the dialog but can’t get that model object instance.
Any help is appreciated.
The solution – With the help of Nick Larsen and Darin Dimitrov
The controller:
[AcceptVerbs(HttpVerbs.Post)]
[Authorize]
public PartialViewResult GetRequest(string requestId)
{
Request request = DatabaseContext.GetRequest(Convert.ToInt32(requestId)) as Request;
return PartialView("Request", request);
}
The view’s Javascript:
function OpenRequest(requestId) {
var methodName = '<%= Url.Content("~")%>' + 'Controller/GetRequest/';
var dataType = "html";
var postData = { requestId: requestId };
var contentType = "application/x-www-form-urlencoded"; ;
var request = ContactServer(methodName, postData, dataType, contentType);
$("#dialog").html(request);
$("#dialog").dialog({ html: request, title: 'Request details...', width: 800, height: 600, modal: true, zindex: 300000, show: 'scale', resizable: false });
}
It’s better to set it up where your view does not call your controller. Load all of the data for the request in the action which calls this view and populate a view model with the needed data. Once you have that, render the fields from the model.
As for your actual problem. The action that calls this view in the first place populates the ViewData.Model for its context. When you call the action method, the framework is creating a new context with its own ViewData which you dont have access to without a handle to that newly created context.