简体   繁体   中英

Pass model name as a parameter

I have a partial view where I pass the model name to populate it, is there any way to pass model name as a parameter based on the controller action executed?

<div id = "Details" >

<% List<Freshmen>() = model based on controller action executed %>

    <% using (Html.BeginForm("FreshmenDetails", "Students")) %>
        <% { %>
<%  Html.RenderPartial("FreshmenDetails", new List<Freshmen>()); %>
        <% } %>
</div>

Controller Action:

    public ActionResult FreshmenDetails(string id)
    {
        DataContext Student = new DataContext();
        var FreshmenDetails = Student.Freshmen.Where(a => Convert.ToInt64(a.Id) == Convert.ToInt64(id)).ToList();

        return PartialView("FreshmenDetails", FreshmenDetails );
    }

I have 3 more Actions each for SophomoreDetails(),JuniorDetails(),SeniorDetails()

Currently I am displaying Partial View like this:

<div id = "Details" >

    <% using (Html.BeginForm("FreshmenDetails", "Students")) %>
        <% { %>
<%  Html.RenderPartial("FreshmenDetails", new List<Freshmen>()); %>
        <% } %>

    <% using (Html.BeginForm("SophomoreDetails", "Students")) %>
        <% { %>
<%  Html.RenderPartial("SophomoreDetails", new List<Sophomore>()); %>
        <% } %>

    <% using (Html.BeginForm("JuniorDetails", "Students")) %>
        <% { %>
<%  Html.RenderPartial("JuniorDetails", new List<Junior>()); %>
        <% } %>

    <% using (Html.BeginForm("SeniorDetails", "Students")) %>
        <% { %>
<%  Html.RenderPartial("SeniorDetails", new List<Senior>()); %>
        <% } %>
</div>

I want something like:

<div id = "Details" >
    <% using (Html.BeginForm("FreshmenDetails", "Students")) %>
        <% { %>
<%  Html.RenderPartial("FreshmenDetails", new List<Freshmen>()); %>
        <% } %>

</div>

I am having a hard time figuring out exactly what your after. That being said, have you tried using reflection?

return PartialView(Model.GetType().Name, new { // Partial View object });

Further more, you can use Model.GetType().Name to get the model object name and use it where you want. That should work for you.

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