我有2个下拉列表,其值应该从数据库中填充。 我检查了存储过程并给出了正确的结果。我甚至调试了控制器,看起来我得到了正确的值。
我需要帮助来搞清楚@ Html.DropDownlistFor语法。我使用的是不正确的。有什么帮助吗?
型号:
public class DropDownConfiguration
{
public string Project { get; set; }
public string LineID { get; set; }
}
控制器:
[ActionName("DetailsForm")]
[HttpGet]
public ActionResult DetailsForm()
{
try
{
IEnumerable<DropDownConfiguration> dropConfig = new List<DropDownConfiguration>();
dropConfig = floorService.DropDownList();
DetailsViewModel model = new DetailsViewModel()
{
dropConfig = dropConfig,
};
return View("DetailsForm",model);
}
catch (Exception ex)
{
return View("_error");
}
}
存储库:
public IEnumerable<DropDownConfiguration> DropDownList()
{
var model = new List<DropDownConfiguration>();
using (var dbCmd = defaultDB.GetStoredProcCommand("dbo.GetLineIDProject"))
{
var varCmd = defaultDB.ExecuteReader(dbCmd);
while (varCmd.Read())
{
model.Add(new DropDownConfiguration()
{
LineID = varCmd.IsDBNull(0) ? "" : varCmd.GetString(0),
Project = varCmd.IsDBNull(1) ? "" : varCmd.GetString(1),
Quarter = varCmd.IsDBNull(2) ? 0 : varCmd.GetInt32(2),
Year = varCmd.IsDBNull(3) ? 0 : varCmd.GetInt32(3)
});
}
}
return model;
}
Html(以下是2个下拉列表LineID,Project)-----需要帮助------
@Html.DropDownListFor(m => m.dropConfig.FirstOrDefault().LineID, "--Select LineID--", new { @class = "form-control" })
@Html.DropDownListFor(m => m.dropConfig.FirstOrDefault().Project, "--Select Project--", new { @class = "form-control" })
答案 0 :(得分:0)
What you need to do, is to create a new select list.
public class DropDownConfiguration
{
public string Project { get; set; }
public string LineID { get; set; }
public SelectList dropDownSelectList{ get; set; }
}
[ActionName("DetailsForm")]
[HttpGet]
public ActionResult DetailsForm()
{
try
{
DropDownConfiguration dropConfig = new DropDownConfiguration();
IEnumrebale<DropDownConfiguration> selectList = floorService.DropDownList();
DetailsViewModel model = new DetailsViewModel()
{
dropConfig = selecrList ,
};
dropConfig.dropDownSelectList = new SelectList(selectList, "Value", "Text");
return View("DetailsForm",model);
}
catch (Exception ex)
{
return View("_error");
}
}
Your View:
@Html.DropDownListFor(m => m.LineID, Model.dropDownSelectList, "--Select LineID--", new { @class = "form-control" })
Your code is unclear. Controller model and repository is not written properly, I have no idea why you have separated the model and create repository class (as business logic should be in the model. There is no clue as to what your DetailsViewModel includes and it seems you have no use for it either.
And when you user first of default in your view the way you did, it means that when you submit the form, you will always get the value of the first field or null, as you didn't populate any values and furthermore if your aim was to populate the drop down list, you would have populated only one field.
Review your code, make the necessary changes as I have shown in the snippet and make sure your code is clear.