【问题标题】:how to use create view for different purpose?如何为不同的目的使用创建视图?
【发布时间】:2012-06-26 13:15:12
【问题描述】:

我是 ASP.NET MVC3 的新手。我使用 Model First 方法在 ASP.NET MVC3 中创建了一个项目。
我有以下实体:CustomerCall

这些实体之间的关系是一个(客户)有多个(电话)。我为这两个实体创建了控制器。

问题在于,在客户的索引视图中,我添加了 ActionLink 来为特定客户添加呼叫。代码如下:

@Html.ActionLink("+Call", "Create", "Call", new { id = item.CustomerId }, null)

点击此链接后,将打开通话的创建视图。在呼叫创建视图中,我想显示特定客户的姓名。
如何使用传递过来的CustomerId?如何做到这一点?

【问题讨论】:

  • 我会为这种情况创建新的操作,例如CreateForCustomer(int id) 具有单独的视图(部分将非常适合弹出窗口)。您可以按照自己的方式使用RouteData 在控制器中提取“id”值,然后从 orm 获取客户信息,然后将其传递给视图(即使用ViewBag)。问题是,在视图中,您必须编写大量剃须刀代码来为两种不同的场景生成 html,并且可能会变得混乱。

标签: .net asp.net-mvc-3 entity-framework ef-model-first


【解决方案1】:

在您的CallController 中更改Create 操作以接受id 参数:

public ActionResult Create(int id)
{
    // TODO: Query the database to get the customer and his name

    // If you use a ViewModel extend it to include the name of the customer
    // Example: viewModel.CustomerName = retrievedCustomer.Name;

    // Or you can pass it in the ViewBag
    // Example: ViewBag.CustomerName = retrievedCustomer.Name;

    return View(viewModel); // or return View();
}

在视图中,您可以根据方法显示名称,如下所示:

@Model.CustomerName

@ViewBag.CustomerName

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-15
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 2020-11-13
    相关资源
    最近更新 更多