【问题标题】:How to pass difference type of model in view?如何在视图中传递不同类型的模型?
【发布时间】:2017-02-14 09:57:30
【问题描述】:

如何传递不同类型的模型(取决于控制器中的返回)来查看?

这是我的控制器:

    public ActionResult Index()
    {
        if (Session["username"] != null)
        {
            if (isAdmin(Session["username"].ToString()))
            {
                return View(db.Branches.ToList());
            }
            else
            {
                int id = db.Users.Find(Session["username"]).branch_id;
                return View(db.Branches.Find(id));
            }
        }
        else
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
    }

如您所见,它可能会返回不同的类型来查看取决于用户是否为管理员。

并且这个视图只是为返回 List Branches 处理的,而不是单个 Branches

@model IEnumerable<Inspinia_MVC5_SeedProject.Models.Branch>
<table class="table table-striped">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.name)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.address)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.create_date)
    </th>
    <th></th>
</tr>
@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.address)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.create_date)
    </td>
    <td>
        @Html.ActionLink("Details", "Details", new { id=item.id }, new { @class = "btn btn-primary btn-sm"})
        @Html.ActionLink("Edit", "Edit", new { id=item.id }, new { @class = "btn btn-white btn-sm"})
        @Html.ActionLink("Delete", "Delete", new { id=item.id }, new { @class = "btn btn-white btn-sm"})
    </td>
</tr>
}
</table>

我已经尝试过了,但是当我返回两种类型的模型时它才有效。不是我想要的。

 @model Tuple<IEnumerable<Inspinia_MVC5_SeedProject.Models.Branch>, Inspinia_MVC5_SeedProject.Models.Branch>

如何在不为其他模型类型创建另一个视图的情况下处理这个问题?谢谢,如果有人可以帮助我,我将非常合适。您可能不需要将所有代码发布给我,只需一些关键字或告诉我如何解决它。

【问题讨论】:

    标签: asp.net view model controller asp.net-mvc-5


    【解决方案1】:

    如果您的View 不会更改并且对于用户管理员 都将保持完全相同,那么您唯一的问题是View接受一个集合,因此解决方案是将单个对象也作为集合传递:-

    else
    {
         int id = db.Users.Find(Session["username"]).branch_id;
         return View(db.Branches.Where(x => x.id == id));
    }
    

    这可确保您的返回类型 id IEnumerable&lt;T&gt; 而不是单个对象,因此您的 View 可以解析它。

    【讨论】:

    • 天啊。你救了我的命。我找了3个多小时没有任何想法,你不到5分钟就解决了。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2017-10-31
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-28
    • 2015-07-27
    相关资源
    最近更新 更多