0

我想做一个下拉列表,当我单击提交按钮时,它会回发选定的值。

我不知道我是否做得对,但到目前为止我已经四处搜索并想出了这个。

我只是想知道我是否做对了,以及一旦它回发它会将值存储在哪里。

@using (Html.BeginForm())
{
    @Html.DisplayName("Name:")<br />
    @Html.TextBox("NAME")<br />

    @Html.DisplayName("Password:")<br />
    @Html.TextBox("PASS")<br />

    @Html.DisplayName("Team Name:")<br />
    @Html.DropDownListFor(x => x.Teams, new SelectList(Model.Teams, "value", "TeamNAME"), new {onchange = "submit()"})

    <input type="submit" value="ADD" />
}

想在这里取值

[HttpPost]
        public ActionResult Index()
        {

            //GET VALUE OF THE SELECTED TEAM HERE
            return RedirectToAction("Index");
        }
4

2 回答 2

2

它看起来非常接近——唯一的一点是,您应该一致地使用模型绑定的 HTML 帮助器方法,或者不使用。也就是说,使用TextBoxForand DropDownListFor, or TextBoxand DropDownList,但不要混用和匹配。

如果您使用模型绑定的,那么您应该能够简单地将模型类型作为参数添加到您的回发操作中:

public ActionResult Index(MyModel postback)

对于未绑定的,您可以使用它们的名称单独添加参数:

public ActionResult Index(string NAME, string PASS, string TEAM)

(假设您将更改为@Html.DropDownList("TEAM", new SelectList(Model.Teams, "value", "TeamNAME"), new {onchange = "submit()"})

于 2012-11-24T06:41:32.110 回答
1

详细信息:以下假设您正在使用一个名为 Team 的模型,并且您正在视图中使用该模型。(代码未测试)

看法

@Html.DropDownListFor("Teams", String.Empty)

控制器

[HttpGet]
public ActionResult Index()
{
    ViewBag.Teams = new SelectList(db.Team, "TeamId", "TeamNAME");
    return View();
}

[HttpPost]
public ActionResult Index(Team team)
{
    // Here is your selected Team id
    //team.TeamId

    return View();
}

查看本教程以获取有关使用 DropDownList 的更多信息

MVC 4 教程

于 2012-11-24T06:41:30.047 回答