【问题标题】:How to set the value of a select field through htmlAttribute in MVC 5?如何在 MVC 5 中通过 htmlAttribute 设置选择字段的值?
【发布时间】:2014-08-17 18:40:46
【问题描述】:

我有一个 ActionLink 定义如下:

@Html.ActionLink("Write a review", "Create", "Reviews")

关键是,当它重定向到Reviews 控制器的Create 视图时,会有一个ID 为BusinessID 的选择字段。因此,我想在打开页面时将选择字段的值设置为特定条目。假设我要设置它的值是毕加索。如何,我可以实现它吗?是否可以使用 htmlAttributes 以某种方式做到这一点?

【问题讨论】:

  • 如果您在重定向页面中选择了 html,您就不能将选项字段设置为“已选择”吗?像这样的东西:<select> <option value = 'Picasso' selected> Picasso </option> </select>?
  • 或者如果我理解正确的话,你想根据你的 ActionLink 在你的 Create.chtml 中设置<select> 标签吗?在这种情况下,您可以在 ReviewController 的 Create 操作中接受参数,然后使用 @Html.ActionLink 的对象 routeValues 发送您希望设置为选中的特定 Id。像这样:@Html.ActionLink("Write a review", "Create", "Reviews", new {id = 1}, null); 然后您的 Create 操作接受此 Id(例如 ActionResult Create(id) { return View(id) })并相应地呈现 Create.chtml 选定的项目。
  • @ShukhratRaimov 是的,我想要第二个选项。虽然我想我需要在 DropDownLink 中提供一个选定的属性。

标签: asp.net-mvc actionlink html.actionlink


【解决方案1】:

您可以在 ReviewsControllerCreate 操作方法中接受所选项目的 id 参数,然后使用 object routeValues 参数>@Html.ActionLink() 发送您想要设置为选中的特定 id。像这样:

@Html.ActionLink("Write a review", "Create", "Reviews", new {id = 1}, null); 

那么您的 Create 操作方法应该接受这个 id(例如:

  public ActionResult Create(int id) 
  { 
      List<SelectListItem> items = new List<SelectListItem>(); //create <option> </option> items of DropDownList
      items.Add(new SelectListItem { Text = "da Vinci", Value = "0", Selected = (id == 0)});
      items.Add(new SelectListItem { Text = "Picasso", Value = "1", Selected = (id == 1)});
      items.Add(new SelectListItem { Text = "van Gogh", Value = "2", Selected = (id == 2)});
      ViewBag.Painters = items;
      return View();
   }

相应地呈现 Create.chtml 选定项:

@Html.DropDownList("Painters")

注意DropDownList 参数("Painters") 应该与ViewBag.Painters 同名。因此,点击链接后,您将获得 Picasso 的选定项目,因为它是 Selected 属性将是 true,因为我们已在 Create action 方法中分配它。

我认为可能有更聪明的方法来编写这个下拉列表,但这种操作方法效果很好。我鼓励您在以下链接上阅读更多关于 @Html.DropDownList 辅助方法的信息:www.asp.netK.Scott Allen。希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 2018-08-28
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    相关资源
    最近更新 更多