【问题标题】:Rename the Model in asp.net mvc在 asp.net mvc 中重命名模型
【发布时间】:2019-01-12 20:19:19
【问题描述】:

我正在尝试使用 Model 将一组对象从控制器传递到视图。

是否可以重命名Model 以便我的视图可读?

例如而不是使用@foreach (var question in Model)

有没有办法说@foreach (var question in questions)

// HomeController.cs

public class HomeController : Controller
{
    public IActionResult Index()
    {
        var repo = new QuestionRepository();
        var questions = repo.FindAll();

        return View(questions);
    }
}

// Index.cshtml

@model IEnumerable<MyDomain.Models.Entity.Question>

<div class="questions-wrap">
    <div class="questions">

        @foreach (var question in Model)
        {
            // Do stuff with the question
        }
    </div>
</div>

【问题讨论】:

  • 不,这是不可能的(除非您在视图顶部使用var questions = Model;),但是为什么您认为使用Model 是不可读的?
  • 这只是我的偏好,但我觉得阅读foreach (question in questions) 比阅读foreach (question in Model) 更有意义。
  • 嗯,呃,它代表模型,对我来说似乎很可读!
  • 是的,没错。无论如何,我认为使用var questions = Model,将满足我的审美要求。如果您可以将其发布为答案,那就太好了。谢谢!
  • 看来@jom 已经抓住了我的代码并回答了。虽然另一种选择是拥有一个具有Questions 属性的模型。

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


【解决方案1】:

如果这让您满意,您可以将其重新分配给一个变量。 :)

@model IEnumerable<MyDomain.Models.Entity.Question>

@{
    var questions = Model;
}

<div class="questions-wrap">
    <div class="questions">

        @foreach (var question in questions)
        {
            // Do stuff with the question
        }
    </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 2014-03-09
    • 2019-05-03
    • 2011-07-23
    相关资源
    最近更新 更多