Creating a dropdown in MVC3 C# with ViewModel and easy model binding on POST back.

廉价感情. 提交于 2019-12-02 16:50:14

问题


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

回答1:


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



回答2:


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



回答3:


List<MvcApplication1.Models.Country> cntry = db.Countries.ToList();
SelectListItem sss = new SelectListItem();
List<SelectListItem> sltst = new List<SelectListItem>();
sss.Text = "Select";
sss.Value = "0";
sltst.Add(sss);
foreach (MvcApplication1.Models.Country s in cntry){
SelectListItem s1 = new SelectListItem();
s1.Text = s.Country1;
s1.Value = Convert.ToString(s.Id);
sltst.Add(s1);}
@Html.DropDownList("country", sltst, new { @id = "country" })


来源:https://stackoverflow.com/questions/9513385/creating-a-dropdown-in-mvc3-c-sharp-with-viewmodel-and-easy-model-binding-on-pos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!