使用 ViewModel 在 MVC3 C# 中创建一个下拉列表,并在 POST 返回时轻松绑定模型。

2023-12-25

我有这个问题,我想为一周中的每一天制作 7 个下拉菜单。 在每个下拉列表中,我希望添加相同的数据。

我的视图模型:

public class WeekDienstCreateViewModel
{
    public WeekDienst weekDienst {get; set;}
    public List<DienstPerWeekDienst> diensten { get; set; }

    public WeekDienstCreateViewModel() { }
}

我在控制器中的创建方法: 正如你所看到的,我已经添加了所有内容,除了 DienstId 之外,它是想通过我的下拉菜单添加的。

 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; }
    }

在我看来,我希望创建 7 个下拉菜单,在其中放入我所有的“Diensten”(Dienst 类,fk in DienstPerWeekDienst)。当我选择 1 时,我希望将“DienstId”添加到“DienstPerWeekDienst”类中​​。

所以在我看来我得到了这个:

            @foreach (var day in Model.diensten)                 
             {   
                  var currentDay=day;
                  @Html.DropDownListFor(currentDropDown=>currentDay, new SelectList(ViewBag.Diensten, "Value", "Text"))                 
             }

我希望回发所选的“Diensten”并创建“WeekDienst”,但现在我只是发布一个空的“DienstPerDienstWeekCreateViewModel”。我怎样才能解决这个问题?

提前致谢

修复(感谢 Siva Gopal)

我通过执行以下操作解决了这个问题:

@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"))
                }

您可以尝试使用

@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 {})                 
 }  //

完整页面提交上的值回发/模型绑定注意事项:为了能够对绑定/POST 返回值到服务器进行建模,与属性相对应的 html 元素名称应呈现如下: 假设如果显示 Employee.Department.Name,则在视图中显示部门名称的文本框名称应该匹配 Department_ReferenceName_Inside_Employee.Name 进行模型绑定。

Model:公开课员工 { 公共 int Id { 得到;放; } 公共字符串名称{获取;放; } 公共字符串城市{获取;放; } 公共部门 EmpDepartment { get;放; } 公共列表子Ordinates { get;放; } } 公开课部 { 公共字符串名称{获取;放; } }

控制器:

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" />    }

查看源代码/页面源代码:上面的文本框语法将呈现为:

<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" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 ViewModel 在 MVC3 C# 中创建一个下拉列表,并在 POST 返回时轻松绑定模型。 的相关文章

随机推荐