Search code examples
c#asp.net-mvcmodel-view-controllerhtml.renderpartial

Using an object returned from Html.RenderAction


I am using Html.RenderAction in my View to call a method that is in my controller. The controller method returns a custom object, I want to know how would I be able to use this returned object in the view.

View

//at the top
@model ServiceCheckerUI.Models.DeleteDeliverableModel

@{ Html.RenderAction("retrieveDeliverableInfo","DeliverableManagement", new {uniqueId = element});}

//Trying to use the model property
Model.deliverableResponse.{properties}

Controller

public ActionResult retrieveDeliverableInfo(string uniqueId){
    var response = _target.DoSomething();
    return PartialView("DeleteDeliverable", new DeleteDeliverableModel {deliverableResponse = response});
}

Model

namespace ServiceCheckerUI.Models
{
    public DeleteDeliverableModel
    {
        //omit
        public GetDeliverableResponse deliverableResponse {get;set}
    }
}

The GetDeliverableResponse object has fields like id, name etc which are strings and ints.


Solution

  • RenderAction is used to directly write response to the page and helps in caching the partial view. Your method should return partial view instead of GetDeliverableResponse. You can define the partial view and use GetDeliverableResponse as it's model.

    public ActionResult RetrieveDeliverableInfo(string uniqueId)
    {
        var response = _target.DoSomething();
        return PartialView("_Deliverable", response );
    }
    

    Here _Derliverable would be your partial view which will have GetDeliverableResponse as model. To keep it more neat you can also Wrap the response object in a dedicated model class of _Derliverable like this:

    class DerliverableModel
    {
       public GetDeliverableResponse Derliverables { get; set; } 
    }
    

    now in your action method you need to pass the object of this model:

    return PartialView("_Deliverable", new DerliverableModel { Derliveries = response });