MVC pass model object from controller to view

前端 未结 3 1573
北海茫月
北海茫月 2021-01-25 00:41

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         


        
相关标签:
3条回答
  • 2021-01-25 01:09

    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.

    0 讨论(0)
  • 2021-01-25 01:10

    You could have the controller action return the partial view:

    <%= Html.Action("GetRequest", "The_Controller", new { requestId = 12 }) %>
    

    And in your controller action:

    public ActionResult GetRequest(int requestId)
    {
        var request = _repository.GetRequest(requestId);
        return PartialView("Request", request);
    }
    

    This way the GetRequest action will pass the request object to the strongly typed Request.ascx partial view and include it in the page at the place you called Html.Action helper.

    0 讨论(0)
  • 2021-01-25 01:20

    It seems that you've got all the necessary information, up front, to create a 'Request' object in your initial controller action method.

    Suggest that:

    • drop the <% Html.Action("GetRequest", "The_Controller", new { requestId = 12 }); %> altogether. We'll be prepopulating ViewData with all the data required to send to the Partial.

    • in your initial controller method, you create a new ViewData entry, perhaps ViewData["SomeRequest"]

    • prepopulate that as you need on the initial controller method, using requestId = 12 and email = "foo@bar", and all the other relevant pieces to create a 'Request' object, or whatever is needed in the Partial View named 'Request'.

      i.e. ViewData["SomeRequest"]= dbRepository.GetRequestById(intrequestId);

    • in your View, call Html.RenderPartial("Request", ViewData["SomeRequest"]);

    0 讨论(0)
提交回复
热议问题