通过在另一个模型的下拉列表中选择一个值来填充类的一个属性
本文关键字:一个 填充 属性 选择 模型 另一个 下拉列表 | 更新日期: 2023-09-27 18:13:21
我有一个类Client,其中有一些属性,特别是一个是restriction_type。另外,我还创建了另一个类restrict,它有一个ID和一个name属性。name属性对应于restriction_type。
然后在下拉列表中显示数据库中所有限制的名称:
@Html.ActionLink("Create New", "Create")
@using (Html.BeginForm("AddRestrictions","Restrictions",FormMethod.Get)){
<p> Type de restriction:
@Html.DropDownList("ClientRestr_type", "All")
</p>
<input type="submit"value="Ajouter"/>
}
这是我的控制器:
public ActionResult AddRestriction(string ClientRestr_type, Restriction restriction)
{
var RestrLst = new List<string>();
var RestrQry = from d in db.Restrictions
orderby d.name
select d.name;
RestrLst.AddRange(RestrQry.Distinct());
ViewBag.ClientRestr_type = new SelectList(RestrLst);
var clients = from c in db.Restrictions select c;
if (string.IsNullOrEmpty(ClientRestr_type))
return View();
else
{
if (ModelState.IsValid)
{
// Here I have maybe to find the way to solve my problem
}
}
所以我想在我的Model Client的restriction_type属性中添加constraint的name属性。
Model Client:
public class Client
{
[Required]
public int ID
{
get;
set;
}
[Required]
public string compte
{
get;
set;
}
[Required]
public string portefeuille
{
get;
set;
}
[Required]
public String restriction_type
{
get;
set;
}
[Required]
public Boolean etat
{
get;
set;
}
public Boolean decision
{
get;
set;
}
模型限制:
public class
{
public int restrictionID
{
get;
set;
}
public string name
{
get;
set;
}
}
你觉得我的GetRestrictions()方法怎么样
private SelectList GetRestrictions()
{
var RestrLst = new List<string>();
var RestrQry = from d in db.Restrictions
orderby d.name
select d.name;
RestrLst.AddRange(RestrQry.Distinct());
return new SelectList(RestrLst);
}
但不幸的是,我有一个错误:不可能转换System.Web.Mvc.SelectList到MyApp.Models.Client行:
模型。
我不明白为什么
谢谢你的帮助!
一个简化的例子:
视图模型public class ClientVM
{
public Client Client { get; set; }
public SelectList RestrictionList { get; set; }
}
控制器[HttpGet]
public ActionResult Create()
{
ClientVM model = new ClientVM();
model.Client = new Client();
model.RestrictionList = GetRestrictions(); // your code to return the select list
return View("Edit", model);
}
[HttpGet]
public ActionResult Edit(int ID)
{
ClientVM model = new ClientVM();
model.Client = // call database to get client based on ID
model.RestrictionList = GetRestrictions();
return View(model);
}
[HttpPost]
public ActionResult Edit(ClientVM model)
{
if (!ModelState.IsValid)
{
model.RestrictionList = GetRestrictions();
return View(model);
}
Client client = model.Client;
// Save and redirect
....
}
视图@model YourNamespace.ClientVM
@using (Html.BeginForm() {
@Html.TextBoxFor(m => m.Client.ID)
@Html.TextBoxFor(m => m.Client.compte)
...
@Html.DropDownListFor(m => m.Client.restriction_type, Model.RestrictionList)
<input type="submit" value="Save" />
}