1

我在数据库表中存储了一个枚举条目,其中只有以下字段:IDName。我想在表单的 DropDownList 中显示存储在此表中的值。然后用户选择一个值并提交表单。

找到了一种从枚举轻松创建 DropDownList 的方法(尽管最好使用表中所有记录的 Name 字段填充 DropDownList)。但是,我还没有找到一种方法将表单提交中的 DropDownList绑定到一个整数值,以便与其他表单值一起放入数据库(FK - PK)。

您能否提供一些示例代码来说明如何进行此类绑定?

更新:感谢您的精彩回答。我还有一个问题:是否可以通过 AJAX 获取 DropDownList 内容并将其放入 DropDownList 和 ViewModel 中的 SelectList 中(同时带有 ID 和 Name 参数)?我想根据用户输入的内容有选择地获取内容,然后我希望 ViewModel 填充该获取的数据。

4

1 回答 1

2

一如既往地从定义模型开始:

public class MyViewModel
{
    public int SelectedValue { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

然后控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            // TODO: Fetch from the database some enumerable collection 
            // containing Id and Name
            Items = new SelectList(new[]
            {
                new { Id = 1, Name = "item 1" },
                new { Id = 2, Name = "item 2" },
            }, "Id", "Name")
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        // TODO: Do something with model.SelectedValue
        return RedirectToAction("index");
    }
}

最后是强类型视图:

<% using (Html.BeginForm()) { %>
    <%: Html.DropDownListFor(x => x.SelectedValue, Model.Items) %>
    <input type="submit" value="OK" />
<% } %>
于 2010-07-04T07:38:33.353 回答