创建于MVC3 C#与视图模型和模型很容易回POST绑定下拉。 [英] Creating a dropdown in MVC3 C# with ViewModel and easy model binding on POST back.
问题描述
我有这个问题,我想,以7下拉菜单为一周的每一天。
在这些下拉列表中的每一个我要补充相同的数据。
我的视图模型:
公共类WeekDienstCreateViewModel
{
公共WeekDienst weekDienst {搞定;组;}
公开名单< DienstPerWeekDienst> diensten {搞定;组; } 公共WeekDienstCreateViewModel(){}
}
我在控制器中创建方法:
就像你看到的我加的一切,除了媒体链接DienstId是想使用我的下拉菜单添加。
公众的ActionResult创建(INT ID)
{
WeekDienst WD = _service.FindWeekDienst(ID);
WeekDienstCreateViewModel VM =新WeekDienstCreateViewModel(); vm.diensten =新的List< DienstPerWeekDienst>();
vm.weekDienst = WD; 的for(int i = 1; I< = 7;我++)
{
DienstPerWeekDienst dpwd =新DienstPerWeekDienst();
dpwd.volgnummer = I;
dpwd.WeekDienstId = wd.Id; vm.diensten.Add(dpwd);
}
ViewBag.Diensten = _service.DienstenList(wd.AfdelingId); 返回查看(VM);
}
类:
公共类DienstPerWeekDienst
{
[键]
公众诠释标识{搞定;组; } [需要]
公众诠释WeekDienstId {搞定;组; } [需要]
公众诠释DienstId {搞定;组; } [需要]
[范围(1,7)]
公众诠释volgnummer {搞定;组; } [ForeignKey的(WeekDienstId)]
公共虚拟WeekDienst WeekDienst {搞定;组; } [ForeignKey的(DienstId)]
公共虚拟丁斯特丁斯特{搞定;组; } 公共虚拟的ICollection< WeekDienst> WeekDiensten {搞定;组; }
} 公共类WeekDienst
{
[键]
公众诠释标识{搞定;组; } [需要]
公众诠释AfdelingId {搞定;组; } [需要]
[StringLength(5,的ErrorMessage =值{0}不能超过{1}个字符。)]
[RegularEx pression(@^ [A-ZA-Z0-9] {5} $的ErrorMessage =Verplicht 5 cijfers郎。)
公共字符串code {搞定;组; } [DisplayName的(模板)]
公共BOOL模板{搞定;组; } [ForeignKey的(AfdelingId)]
公共虚拟Afdeling Afdeling {搞定;组; }
}
在我看来,我希望创建7下拉菜单,其中我把我所有的Diensten(类丁斯特,FK在DienstPerWeekDienst)。当我选择1我要补充的DienstId变成了DienstPerWeekDienst级。
所以,在我看来,我得到这个:
@foreach(VAR日Model.diensten)
{
VAR CURRENTDAY =天;
@ Html.DropDownListFor(currentDropDown => CURRENTDAY,新的SelectList(ViewBag.Diensten,值,文本))
}
我要回发选择了Diensten,创造了WeekDienst,但现在我只是张贴空DienstPerDienstWeekCreateViewModel。我怎么能解决这个问题?
由于提前
FIX(感谢湿婆戈帕尔)
我解决了这个问题做:
@for(INT I = 0; I< @ Model.diensten.Count;我++)
{
@ Html.HiddenFor(M =>(m.diensten [I] .volgnummer))
@ Html.HiddenFor(M =>(m.diensten [I] .WeekDienstId))
@ Html.DropDownListFor(M =>(m.diensten [I] .DienstId),新的SelectList(ViewBag.Diensten,值,文本))
}
您可以尝试使用
@foreach(VAR日Model.diensten)
{
VAR CURRENTDAY =天;
@ Html.DropDownListFor(currentDropDown => CURRENTDAY,新的SelectList(ViewBag.Diensten,PropertyName_Holding_Value,PropertyName_Holding_DisplayText),新{})
} //这里使用拉姆达防爆pression。您的下拉名称/ ID将根据CURRENTDAY值是1,2,3等。
或
@foreach(VAR日Model.diensten)
{
VAR CURRENTDAY =天;
变种dropdownName =的String.Format(diensten [{0}],日-1); //如果你想绑定模型在POST请求所选择的下拉列表值输入实体。最后dropdownName格式应符合输入实体/对象中的属性的层次结构。即使没有这个名字的形成,仍然可以回发使用Jquery / JavaScript中的选定值。
@ Html.DropDownList(dropdownName,新的SelectList(ViewBag.Diensten,PropertyName_Holding_Value,PropertyName_Holding_DisplayText),新{})
} //
注意了价值邮报整版回/模型绑定提交:
为了能够模拟绑定/ POST回值到服务器,对应的属性的HTML元素的名称应该呈现如下:假设,如果你显示Employee.Department.Name,那么文本框的名称,视图显示部门名称应匹配Department_ReferenceName_Inside_Employee.Name为模型绑定。
型号:
公共类员工
{
公众诠释标识{搞定;组; }
公共字符串名称{;组; }
公共字符串城{搞定;组; }
公共部门EmpDepartment {搞定;组; }
公开名单下属{搞定;组; }
}
公共类系
{
公共字符串名称{;组; }
}
控制器:
公共类HomeController的:控制器
{
公众的ActionResult指数()
{
ViewBag.Message =欢迎使用ASP.NET MVC!; // prepare模型,并将其发送到视图
员工EMP =新员工{EmpDepartment =新部门{名称=IT}};
emp.SubOrdinates =新的List<员工> {新员工{名称=EMP1},新员工{名称=EMP2}};
返回查看(EMP);
} [HttpPost]
公众的ActionResult指数(员工EMP)
{//此处将一个破发点,看看鉴于修改后的值流入EMP ..
返回查看(EMP);
}
公众的ActionResult关于()
{
返回查看();
}
}
查看:
@model MvcApplication.Models.Employee
@using(Html.BeginForm())
{ @ Html.TextBoxFor(M = GT; m.EmpDepartment.Name)
@ Html.LabelForModel(下属:)
的for(int i = 0; I< @ Model.SubOrdinates.Count;我++)
{
@ Html.TextBoxFor(M =>(m.SubOrdinates [I] .Name点))
}
<输入类型=提交名称=名字值=提交/> }
ViewSource / PageSource:
以上文本框语法将呈现为:
<输入ID =EmpDepartment_NameNAME =EmpDepartment.Name类型=文本值=IT/> < - 见上面的html:名称= EmpDepartment.Name - >
<标签=>下属:LT; /标签>
<输入ID =SubOrdinates_0__NameNAME =下属[0] .Name点类型=文本VALUE =EMP1/>
<输入ID =SubOrdinates_1__NameNAME =下属[1] .Name点类型=文本VALUE =EMP2/> <! - 请参阅上面的html如何收集项目姓名(或名称)正在视图引擎renderd - >
<输入类型=提交名称=名字值=提交/>
I have this problem where i want to make 7 dropdowns for each day of the week. In each one of those dropdowns i wish to add the same data.
My ViewModel:
public class WeekDienstCreateViewModel
{
public WeekDienst weekDienst {get; set;}
public List<DienstPerWeekDienst> diensten { get; set; }
public WeekDienstCreateViewModel() { }
}
My Create Method in Controller: As u can see I add everything allready except DienstId which is want to add with my dropdowns.
public ActionResult Create(int id)
{
WeekDienst wd = _service.FindWeekDienst(id);
WeekDienstCreateViewModel vm = new WeekDienstCreateViewModel();
vm.diensten = new List<DienstPerWeekDienst>();
vm.weekDienst = wd;
for (int i = 1; i <= 7; i++)
{
DienstPerWeekDienst dpwd = new DienstPerWeekDienst();
dpwd.volgnummer = i;
dpwd.WeekDienstId = wd.Id;
vm.diensten.Add(dpwd);
}
ViewBag.Diensten = _service.DienstenList(wd.AfdelingId);
return View(vm);
}
Classes:
public class DienstPerWeekDienst
{
[Key]
public int Id { get; set; }
[Required]
public int WeekDienstId { get; set; }
[Required]
public int DienstId { get; set; }
[Required]
[Range(1, 7)]
public int volgnummer { get; set; }
[ForeignKey("WeekDienstId")]
public virtual WeekDienst WeekDienst { get; set; }
[ForeignKey("DienstId")]
public virtual Dienst Dienst { get; set; }
public virtual ICollection<WeekDienst> WeekDiensten { get; set; }
}
public class WeekDienst
{
[Key]
public int Id { get; set; }
[Required]
public int AfdelingId { get; set; }
[Required]
[StringLength(5, ErrorMessage = "Value for {0} cannot exceed {1} characters.")]
[RegularExpression(@"^[a-zA-Z0-9]{5}$", ErrorMessage = "Verplicht 5 cijfers lang.")]
public string code { get; set; }
[DisplayName("Template")]
public bool template { get; set; }
[ForeignKey("AfdelingId")]
public virtual Afdeling Afdeling { get; set; }
}
And in my view i wish to create 7 dropdowns where i put in all my "Diensten" (class Dienst, fk in DienstPerWeekDienst). When I choose 1 i wish to add the "DienstId" into the "DienstPerWeekDienst" class.
So in my View i got this:
@foreach (var day in Model.diensten)
{
var currentDay=day;
@Html.DropDownListFor(currentDropDown=>currentDay, new SelectList(ViewBag.Diensten, "Value", "Text"))
}
I Wish to postback the chosen "Diensten" and create the "WeekDienst" but now i am just posting a null "DienstPerDienstWeekCreateViewModel". How am I able to fix this?
Thanks in Advance
FIX (Thanks to Siva Gopal)
I fixed this by doing:
@for (int i = 0; i < @Model.diensten.Count; i++)
{
@Html.HiddenFor(m => (m.diensten[i].volgnummer))
@Html.HiddenFor(m => (m.diensten[i].WeekDienstId))
@Html.DropDownListFor(m=> (m.diensten[i].DienstId), new SelectList(ViewBag.Diensten, "Value", "Text"))
}
You may try using
@foreach (var day in Model.diensten)
{
var currentDay=day;
@Html.DropDownListFor(currentDropDown=>currentDay, new SelectList(ViewBag.Diensten, "PropertyName_Holding_Value", "PropertyName_Holding_DisplayText"), new { })
} //This uses the Lambda Expression. Your dropdown Name/Id would be 1,2,3 etc. based on currentDay value.
OR
@foreach (var day in Model.diensten)
{
var currentDay=day;
var dropdownName=string.Format("diensten[{0}]",day-1); //If you want to model bind the selected dropdown value to input entity in POST request. The final dropdownName format should match the hierarchy of the property inside input entity/object. Even without this name formation, you can still POST the selected value back using Jquery/Javascript.
@Html.DropDownList(dropdownName, new SelectList(ViewBag.Diensten, "PropertyName_Holding_Value", "PropertyName_Holding_DisplayText"), new {})
} //
Note for Value Post back/model bind on full Page submit: To be able to model bind/POST back values to the server, the html element names corresponding to the properties should be rendered as follows: Suppose if you display Employee.Department.Name, then name of textbox, displaying the Department Name in View should match Department_ReferenceName_Inside_Employee.Name for model binding.
Model: public class Employee { public int Id { get; set; } public string Name { get; set; } public string City { get; set; } public Department EmpDepartment { get; set; } public List SubOrdinates { get; set; } } public class Department { public string Name { get; set; } }
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
//Prepare the model and send it to the view
Employee emp = new Employee { EmpDepartment = new Department { Name = "IT" } };
emp.SubOrdinates = new List<Employee> { new Employee { Name = "Emp1" }, new Employee { Name = "Emp2" } };
return View(emp);
}
[HttpPost]
public ActionResult Index(Employee emp)
{ //Put a break-point here and see how the modified values in view are flowing into emp..
return View(emp);
}
public ActionResult About()
{
return View();
}
}
View:
@model MvcApplication.Models.Employee
@using (Html.BeginForm())
{
@Html.TextBoxFor(m => m.EmpDepartment.Name)
@Html.LabelForModel("SubOrdinates :")
for (int i = 0; i < @Model.SubOrdinates.Count; i++)
{
@Html.TextBoxFor(m => (m.SubOrdinates[i].Name))
}
<input type="submit" name="name" value="Submit" /> }
ViewSource/PageSource: The above text box syntax will be rendered as :
<input id="EmpDepartment_Name" name="EmpDepartment.Name" type="text" value="IT" /> <!--See above html : name=EmpDepartment.Name -->
<label for="">SubOrdinates :</label>
<input id="SubOrdinates_0__Name" name="SubOrdinates[0].Name" type="text" value="Emp1" />
<input id="SubOrdinates_1__Name" name="SubOrdinates[1].Name" type="text" value="Emp2" /> <!--See above html for how collection item Name(s) are being renderd by view engine-->
<input type="submit" name="name" value="Submit" />
这篇关于创建于MVC3 C#与视图模型和模型很容易回POST绑定下拉。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!