以编程方式在ASP.NET MVC中使用多个HTML Select控件

目录

介绍

使用代码

使用JQuery

使用Razor和C#

兴趣点


介绍

很多时候,我们使用JavaScriptJQuery代码来操纵HTML控件,却不知道ASP.NET MVCRazorC#的结合有多强大,或者不知道两种方式都能做到这一点。

下面是这两种方式,一种经典的JQuery方式,也可以在PHPJSP等中使用。

使用代码

这是一个常见的多个HTML选择控件:

@* Home\Index.cshtml *@

<select name='categories' id="selectCategories" multiple>
  <option value="1">Meat</option>
  <option value="2">Cereals</option>
  <option value="3">Seafood</option>
  <option value="4">Soda</option>
  <option value="5">Coffee</option>
</select>

我们需要以编程方式选择许多选项,例如:Meat1),Cereals2)和Soda4)。

使用JQuery

使用JQuery,我们需要在同一HTML页面或JavaScript文件中创建JavaScript标记,并在页面中添加引用,在本文中,它已用于第二种方式:

// Index.js

$(document).ready(function () {
    selectItems();
});
function selectItems() {
    var values = "1,2,4";
    $.each(values.split(","), function (i, e) {
        $("#selectCategories option[value='" + e + "']").prop("selected", true);
    });
}

在这一行中,我们需要选择以下选项:

var values = "1,2,4";

使用RazorC

这是我们要在HTML选择控件中加载的Model类:

// Category.cs

public class Category
{
   public int Id { get; set; }
   public string Name { get; set; }
}

Controller这使得填充select控制和选择:

// HomeController.cs

public ActionResult Index()
{
     List<Category> categories = new List<Category>();
     Category category = new Category();
     category.Id = 1;
     category.Name = "Meat";
     categories.Add(category);
     category = new Category();
     category.Id = 2;
     category.Name = "Cereals";
     categories.Add(category);
     category = new Category();
     category.Id = 3;
     category.Name = "Seafood";
     categories.Add(category);
     category = new Category();
     category.Id = 4;
     category.Name = "Soda";
     categories.Add(category);
     category = new Category();
     category.Id = 5;
     category.Name = "Coffee";
     categories.Add(category);
     ViewBag.Categories = new MultiSelectList(categories, "Id", "Name", new[] { 1, 2, 4 });
     return View();
}

MultiSelectList对象允许选中并将List所有选项传递给Home\Index.cshtml

ViewBag.Categories = new MultiSelectList(categories, "Id", "Name", new[] { 1, 2, 4 });

Home\Index.cshtml,我们可以使用空的HTML select控件,并在Razor中使用forwhile循环语句用ViewBag.Categories填充:

<select name='categories' id="selectCategories" multiple/>

或使用Razor HTML Helpers

<h2>Multiselect with Razor (DropDownList)</h2>
@Html.DropDownList("Id", (MultiSelectList)ViewBag.Categories, new { multiple = "multiple" })
<h2>Multiselect with Razor (ListBox)</h2>
@Html.ListBox("Id", (MultiSelectList)ViewBag.Categories)

兴趣点

就个人而言,我更喜欢Razor HTML Helper,可以解决许多缺少功能且减少了代码行的HTML控件。

发布了69 篇原创文章 · 获赞 133 · 访问量 44万+

猜你喜欢

转载自blog.csdn.net/mzl87/article/details/104113643