简体   繁体   中英

MVC Partial view to Display list

I have an Action result that returns a list

public ActionResult GetData(Profiles profiles)
{
    Vertical Vdata = new Vertical();
    List<Ver> Vertical = new List<Ver>();
       //Code to fill list
    return View(Vertical);
}

And then a partial view to display the List

@model  IEnumerable< List<VerticalContainer.Models.Vertical>>

@foreach(var item in Model)
{
 <span>@item.name</span>
}

I'm not sure how to render the partial view from my main view

@Html.Action("GetData")?? 

What do I pass with the Html.Action? or Should I use Partial/RenderPartial?

1- the correct way to render actions is as per the following:

@Html.RenderAction("ACTION_NAME","CONTROLLER_NAME")

where you replace both action name and controller name with the correct values according to your solution.

2- For the passed model, if this action is being rendered inside a view that has a Model property of Profiles , then you don't have to specify the model to be passed to the action, as it will implicitly read it from the parent view.

if this is not the case, then you will need to store your Profiles values inside a medium variable (for example inside a ViewBag property) and then you will pass it when calling the action, so it should work on this passed model istead of working on the parent view one.

example: @Html.RenderAction("ACTION_NAME","CONTROLLER_NAME", YOUR_MODEL_VALUE_HERE)

Suggestion : if this parital view will just render the list passed, you can skip creating the mentioned action, and just make a call which can render the partial view, passing to it the correct list so it can work with.

To make it more clear, using your question I can see that the action named GetData is just constructing the list called Vertical from the Profiles model passed, so you can construct this list in your original action ( Index , Details , WHAT_EVER_THE_NAME_IS ) and store it in a ViewBag , then you can call RenderParial instead of RenderAction and this should result in the same output as your mentioned scenario.

example: @{ Html.Partial("ViewName", YOUR_MODEL_HERE);}
@{Html.RenderAction("actionName","controllerName");}

From your main view, you may simply render your Partial view as:

 @Html.Partial("_PartialViewName", VerticalList);

VerticalList in this case will be the list of type VerticalContainer.Models.Vertical , that you populated in controller action.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM