首页 > 解决方案 > 如何将从 DropDownList 中选择的值传递给控制器​​ - MVC

问题描述

我无法在 Homecontroller 的下拉列表中选择值。我有一个表单中的 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" />
}

有任何想法吗?运行时没有错误,我只是不知道如何获得响应。

标签: htmlasp.net-mvcmodel-view-controllerdrop-down-menuview

解决方案


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

例子:

模型:

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)接收相同类型视图模型的操作,MVC 会自动为您绑定它

此致


推荐阅读