gpt4 book ai didi

asp.net-mvc - 如何获得强类型的 DropDownList 以绑定(bind)到控件 Action

转载 作者:行者123 更新时间:2023-12-05 01:20:53 25 4
gpt4 key购买 nike

我刚刚开始一个新的 MVC 项目,但我无法从表单中获取发布结果。

这是我的模型类:

public class User
{
public int id { get; set; }

public string name { get; set; }
}

public class TestModel
{
public List<User> users { get; set; }
public User user { get; set; }
public SelectList listSelection { get; set; }

public TestModel()
{
users = new List<User>()
{
new User() {id = 0, name = "Steven"},
new User() {id = 1, name = "Ian"},
new User() {id = 2, name = "Rich"}
};

listSelection = new SelectList(users, "name", "name");
}
}

这是我的 View 类

@model MvcTestApplicaiton.Models.TestModel

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>
@using (Html.BeginForm())
{
@Html.DropDownListFor(x => x.user, @Model.listSelection)

<p>
<input type="submit" value="Submit" />
</p>
}

@if (@Model.user != null)
{
<p>@Model.user.name</p>
}

这是我的 Controller :

public class TestModelController : Controller
{
public TestModel model;
//
// GET: /TestModel/

public ActionResult Index()
{
if(model ==null)
model = new TestModel();

return View(model);
}

[HttpPost]
public ActionResult Test(TestModel test)
{
model.user = test.user;

return RedirectToAction("index", "TestModel");
}

}

下拉列表显示正常,但我看不到要运行 ActionResult 测试函数。我以为它只会用反射来约束自己,但不管有什么问题,我都看不到。

最佳答案

您的代码中有两个主要错误。

  1. 正如 Brett 所说,您正在使用 Index 方法进行发布,但您没有支持 POST 动词的 Index 方法。最简单的修复方法是将 Html.BeginForm() 更改为 Html.BeginForm("Test", "TestModel")
  2. 您以错误的方式使用了 Html.DropDownListFor。您可以在那里只传递一个值类型,因为不要忘记 View 将生成一个 HTML 页面。因此,在您的模型中,您应该有一个 UserID 而不是 User,而在您的 View 中,您应该有 @Html.DropDownListFor(x => x.UserID, @Model.listSelection)。最后,在您的 Action 中,您应该查询数据源以获取具有此 ID 的用户的详细信息。

希望这对您有所帮助。

关于asp.net-mvc - 如何获得强类型的 DropDownList 以绑定(bind)到控件 Action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21702814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com