用 URL 参数替换 MVC 中的下拉列表
Replacing a drop down list in MVC with a URL parameter
我有一些理论问题,因为我不太确定从哪里开始编写这个代码,这也使得 Google 变得困难。我有两个模型,一个帐户模型和一个小说模型,到目前为止我已经使用代码优先开发来设置它。
我创建了一个 'Add Novel' 视图,方法是使用 Entity Framework 创建一个 'Create' 视图,并为帐户 ID 外键创建了一个正确的下拉列表,但是我想要做的是 select 这个值基于通过路由传入的值,因此它会在创建新对象时自动添加。
我猜这意味着我需要更改路由配置中的路由,但不确定如何以及如何在创建对象时将其注册为帐户 ID 所以任何帮助这将是受欢迎的。
不需要修改路由。您可以通过更改 Create()
方法来使用默认路由以接受帐户 ID
public NovelController : Controller
{
public ActionResult Create(int ID)
{
// Get the account based on the value of ID
// Initialize a new Novel view model and set the parent account properties you need to display in the view
// return the view
}
然后使用 ../Novel/Create/#
导航到它,其中 #
是帐户的 ID,例如在帐户 'Details' 视图中,您可能有
@model Account
...
@Html.ActionLink("Create Novel", "Create" "Novel", new { id = Model.AccountID })
我有一些理论问题,因为我不太确定从哪里开始编写这个代码,这也使得 Google 变得困难。我有两个模型,一个帐户模型和一个小说模型,到目前为止我已经使用代码优先开发来设置它。
我创建了一个 'Add Novel' 视图,方法是使用 Entity Framework 创建一个 'Create' 视图,并为帐户 ID 外键创建了一个正确的下拉列表,但是我想要做的是 select 这个值基于通过路由传入的值,因此它会在创建新对象时自动添加。
我猜这意味着我需要更改路由配置中的路由,但不确定如何以及如何在创建对象时将其注册为帐户 ID 所以任何帮助这将是受欢迎的。
不需要修改路由。您可以通过更改 Create()
方法来使用默认路由以接受帐户 ID
public NovelController : Controller
{
public ActionResult Create(int ID)
{
// Get the account based on the value of ID
// Initialize a new Novel view model and set the parent account properties you need to display in the view
// return the view
}
然后使用 ../Novel/Create/#
导航到它,其中 #
是帐户的 ID,例如在帐户 'Details' 视图中,您可能有
@model Account
...
@Html.ActionLink("Create Novel", "Create" "Novel", new { id = Model.AccountID })