如何将从 DropDownList 中选择的值传递给控制器​​ - MVC

How to pass value selected from DropDownList to Controller - MVC

我无法在家庭控制器的下拉列表中选择值。我有表单中的 DropDownList,但我认为我的格式可能有误。我是 MVC 的新手,也是 HTML 的新手,所以我很努力。非常感谢您的帮助。

这是我的控制器(我把它放在我的家庭控制器里,这是个坏主意吗?):

public IActionResult Index()
{
    _ = new List<MyjsonSettings>();
    var obj = new StatusPortController(configuration);
    List<MyjsonSettings> PortList = obj.GetPortNum();
    List<SelectListItem> AppNameList = PopulateDropDown(PortList);
    
    ViewData["Applications"] = AppNameList;
    
    return View("~/Views/Home/dataview.cshtml");
}
    
public List<SelectListItem> PopulateDropDown(List<MyjsonSettings> PortList)
{
    List<SelectListItem> AppNameList = new List<SelectListItem>();
    
    for (int i = 0; i < PortList.Count(); i++)
    {
        AppNameList.Add(new SelectListItem {
            Text = PortList[i].NAME, Value = (i+1).ToString()
        });
    }
    
    return AppNameList;
}

这是视图 (dataview.cshtml):

@{
   ViewData["Title"] = "Home Page";
}


@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    @Html.DropDownList("Applications", ViewData["AppNameList"] as List<SelectListItem>)

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

有什么想法吗?我 运行 时没有错误,我只是不知道如何取回响应。

您可以将结构重建为更有用的方式,并且为了提交带有下拉列表或任何类型字段的表单,您需要首先 return 带有模型的视图,然后将表单提交给接收与参数相同模型类型的操作

示例:

型号:

public class ApplicationsAddModel {
     public ApplicationsAddModel (){
           //constructer to initialize the list 
           ApplicationsList  = new List<SelectListItem>();
     }
 
     public string test{ get; set; }     
     public int selectedApplicationId { get; set; }         
     public List<SelectListItem> ApplicationsList { get; set; } 
}

控制器

//this is the first action that return the model 
[HttpGet]
public IActionResult Index()
{
    ApplicationsAddModel model = new ApplicationsAddModel (); 
    //fill your drop down list
    List<SelectListItem> AppNameList = PopulateDropDown(PortList);
    model.ApplicationsList = AppNameList;
    return View(model);
}

[HttpPost] //recive the form
public IActionResult Index(ApplicationsAddModel SubmittedModel)
{
    var selectedApplication = SubmittedModel.selectedApplicationId; //get the selected value from ddl

    //fill your drop down list
    List<SelectListItem> AppNameList = PopulateDropDown(PortList);
    model.ApplicationsList = AppNameList;
    return View(SubmittedModel);
}

查看 (index.cshtml):

@model projectName.ApplicationsAddModel 
@{ ViewData["Title"] = "Home Page"; }

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{  
      @Html.LabelFor(m => m.selectedApplicationId)
      @Html.DropDownListFor(m => m.selectedApplicationId, Model.ApplicationsList, "---", new { @class = "custom-select form-control" }) 
      <input type="submit" value="submit" />
}

总结: 在 MVC 中,当您必须向控制器提交数据、创建模型、转到控制器并创建您的第一个操作 (GET),用初始数据填充表单并填充下拉列表(如果存在),然后创建 (POST) 接收同类型view模型的action,MVC会自动为你绑定

此致