C# 如何接收在后端代码中选择的下拉值
我是新的网页开发和学习下拉HTML助手。因此,我创建了下拉列表,但无法在后端接收所选值 下面是我的尝试 视图:C# 如何接收在后端代码中选择的下拉值,c#,asp.net,asp.net-mvc,drop-down-menu,asp.net-mvc-5,C#,Asp.net,Asp.net Mvc,Drop Down Menu,Asp.net Mvc 5,我是新的网页开发和学习下拉HTML助手。因此,我创建了下拉列表,但无法在后端接收所选值 下面是我的尝试 视图: @model WebApplication3.Models.DropDownViewModel <form method="post"> @Html.DropDownListFor(m => m.SongList, new SelectList(Model.SongList, "Value", "Text"), "Select menu", new { @cl
@model WebApplication3.Models.DropDownViewModel
<form method="post">
@Html.DropDownListFor(m => m.SongList, new SelectList(Model.SongList, "Value", "Text"), "Select menu", new { @class = "form-control" })
@* below is the use of each argument.*@
@*1. m=>m.SongList => It helps in strongly typing to the model*@
@*2. Model.SongList => It is the datasource for creating the dropdown*@
@*3. "Value" => This is the value behind each of the dropdown options*@
@*4. "Text" => This is the actual text*@
@*5. "Select Menu" => This is the first option that will appear in the dropdown*@
<input type="submit" value="Send" />
</form>
您需要在DropDownViewModel中添加一个属性来检索选定的值
public class DropDownViewModel
{
public DropDownViewModel()
{
SongList = new List<SelectListItem>();
}
public int Id { get; set; }
public string SelectedSongId { get; set; }
public List<SelectListItem> SongList { get; set; }
}
您需要在DropDownViewModel中添加一个属性来检索选定的值
public class DropDownViewModel
{
public DropDownViewModel()
{
SongList = new List<SelectListItem>();
}
public int Id { get; set; }
public string SelectedSongId { get; set; }
public List<SelectListItem> SongList { get; set; }
}
为什么不直接使用适当的注释呢?我会在HttpPost中放置一个断点,看看运行对象时该对象是什么样子。@davidele:添加了注释tag@DavidLee:你能告诉我哪里出了错吗?@牢不可破没有错,奇怪的是为什么没有使用注释。例如,您的C#代码中仍然有*而不是//或/**/。为什么不使用正确的注释呢?我会在HttpPost中放置一个断点,然后查看对象在运行时的样子。@Davidle:添加了注释tag@DavidLee:你能告诉我哪里出了错吗?@牢不可破没有错,奇怪的是为什么没有使用注释,例如,您的C#代码中仍然有*而不是//或/**/。因此,基本上,第一个参数是存储所选值的位置<代码>模型=>模型。选择歌曲ID是,正确。是另一个例子。所以基本上,第一个参数是存储所选值的位置<代码>模型=>模型。选择歌曲ID是,正确。这是另一个例子。
public class DropDownViewModel
{
public DropDownViewModel()
{
SongList = new List<SelectListItem>();
}
public int Id { get; set; }
public string SelectedSongId { get; set; }
public List<SelectListItem> SongList { get; set; }
}
@using (Html.BeginForm())
{
@Html.DropDownListFor(model => model.SelectedSongId, Model.SongList, new { @class = "form-control" })
<button type="submit" value="Submit" class="btn btn-primary">Submit</button>
}
[HttpPost]
public ActionResult Index(DropDownViewModel viewModel)
{
var id = viewModel.SelectedSongId;
...
}