我有一个DropDownConfiguration模型,它从数据库中获取值并填充下拉列表。
型号:
public class DropDownConfiguration
{
public int ID { get; set; }
public int Quarter { get; set; }
public int Year { get; set; }
public string Project { get; set; }
public string LineID { get; set; }
}
HTML:
@Html.DropDownList("Project", new SelectList(Model.dropConfig, "ID", "Project"), "-- Select Project --", new { required = true, @class = "form-control" })
我有另一个模型DetailsConfiguration,它包含需要保存到数据库中的所有字段。
public class DetailsConfiguration
{
public int Quarter { get; set; }
public int Year { get; set; }
public string Project { get; set; }
public string ItemModel { get; set; }
}
Controller HttpPost:
[ActionName("DetailsForm")]
[HttpPost]
public ActionResult DetailsForm(DetailsViewModel model, FormCollection form)
{
DetailsConfiguration detailsConfig = new DetailsConfiguration();
detailsConfig.Quarter = Convert.ToInt32(form["Quarter"]);
detailsConfig.Year = Convert.ToInt32(form["Year"]);
detailsConfig.Project = model.detailsConfig.Project;
detailsConfig.ItemModel = model.detailsConfig.ItemModel;
detailsConfig.LineID = model.detailsConfig.LineID;
floorService.SaveDetails(detailsConfig);
ModelState.Clear();
ViewBag.message = "Success";
return View("DetailsForm");
}
无论如何都要做类似的事情:
model.detailsConfig.Project = model.dropConfig.Project
我需要通过DetailsConfiguration将项目选择回发到数据库。
答案 0 :(得分:0)
您可以创建一个映射器,将DropDownConfiguration
中的属性值设置为DetailsConfiguration
。
更改下拉列表时,将选定的DropDownConfiguration
发送到服务器。你确切知道你可以在这里找到什么属性,所以你可以这样做:
[HttpPost]
public IHttpActionResult AddDetailsConfiguration(DropDownConfiguration parameter)
{
//check here if values in parameter are set
var detailsConfiguration = new DetailsConfiguration {
Quarter = parameter.Quarter,
Year = parameter.Year,
Project = parameter.Project
}
//Insert detailsConfiguration to database
Return Ok();
}
请注意,您必须确保在选择下拉项时发送DropDownConfiguration对象。您也可以只发送您需要的值:
[HttpPost]
public IHttpActionResult AddDetailsConfiguration(int quarter, int year, string project)
{
//Check here if values in parameter are set and if values are correct
var detailsConfiguration = new DetailsConfiguration
{
Quarter = quarter,
Year = year,
Project = project
}
//Insert detailsConfiguration to database
Return Ok();
}