ASP.NET MVC PresentationModel Binding to ComboBoxes stays empty - c#

Hello I'm learning to program MVC style in ASP.NET. I'm trying to populate a combobox with my PresentationModel, somehow it stays empty.
I'm using the ASP tag-helpers:
View (Index.cshtml)
#model Week3_oef2_ITPro.PresentationModel.PMRegistration
<h2>New Registration</h2>
<h4>Registration</h4>
<form asp-controller="Register" asp-action="" method="post">
<table>
<tr>
<td>Organization</td>
<td class="form-group">
<select asp-for="OrgId.Id" asp-items="#Model.Org" class="form-group" />
</td>
</tr>
<tr><td><input type="submit" /></td></tr>
</table>
</form>
PresentationModel (PMRegistration.cs)
public class PMRegistration
{
public Organization OrgId { get; set; }
public List<SelectListItem> Org { get; set; }
}
Model (Organization.cs)
public class Organization
{
public int Id { get; set; }
public string Name { get; set; }
}
Data (Where all the objects are initialized)
public class Data
{
private static List<Session> sessions = new List<Session>();
private static List<Organization> organizations = new List<Organization>();
private static List<Device> devices = new List<Device>();
static Data()
{
organizations.Add(new Organization() { Id = 1, Name = "Howest" });
organizations.Add(new Organization() { Id = 2, Name = "Vives" });
organizations.Add(new Organization() { Id = 3, Name = "HoGent" });
organizations.Add(new Organization() { Id = 4, Name = "HoLimburg" });
organizations.Add(new Organization() { Id = 4, Name = "De blauwe smurfen" });
devices.Add(new Device() { Id = 1, Name = "Laptop" });
devices.Add(new Device() { Id = 2, Name = "Tablet" });
devices.Add(new Device() { Id = 3, Name = "Apple Watch" });
}
public static List<Device> GetDevices()
{
return devices;
}
public static List<Organization> GetOrganizations()
{
return organizations;
}
}
Controller (RegisterController.cs)
public class RegisterController : Controller
{
// GET: /<controller>/
[HttpGet]
public IActionResult Index()
{
PMRegistration pm = new PMRegistration();
pm.OrgId = new Organization();
pm.Org = ConverToListItems(Data.GetOrganizations());
return View(pm);
}
#region methodes
private List<SelectListItem> ConverToListItems(List<Organization> data)
{
List<SelectListItem> items = new List<SelectListItem>();
foreach (var item in data)
{
items.Add(new SelectListItem() { Text = item.Name, Value = item.Id.ToString() });
}
return items;
}
#endregion
}

Your HTML markup for the SELECT element is wrong. The SELECT element requires a closing tag.
It should be
<select asp-for="OrgId.Id" asp-items="#Model.Org" class="form-group"></select>

Related

Input type radio for creating object in many-to-many relationship mvc

I have 3 models: Component, Category (categories of the components) and Sistem.
I want to create a Sistem using already existing components. In the create view I want to use radio input to select the Component, but it seems like the selected one doesn't go where it should.
I have two models that have a many-to-many relationship:
public class Sistem
{
public Sistem()
{
this.Components = new HashSet<Component>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Component> Components { get; set; }
}
public class Component
{
public Component()
{
this.Sistems = new HashSet<Sistem>();
}
public int Id { get; set; }
public int Name {get; set; }
public ICollection<Sistem> Sistems { get; set; }
}
public ActionResult Create()
{
Sistem sistem = new Sistem();
var categories = from cat in db.Categories select cat;
ViewBag.Categories = categories;
sistem.Components = CreateAllComponents();
return View(sistem);
}
public ActionResult Create(Sistem sistem)
{
var categories = from cat in db.Categories select cat;
ViewBag.Categories = categories;
if (ModelState.IsValid)
{
db.Sisteme.Add(sistem);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return View(sistem);
}
}
[NonAction]
public ICollection<Component> CreateAllComponents()
{
Component empty = new Component();
var listOfComponents = new List<Component>();
var categories = from cat in db.Categories
select cat;
foreach (var cat in categories)
{
listOfComponents.Add(empty);
}
return listOfComponents;
}
Now I want to choose one Component from each Category and add it to the Sistem collection of Categories.
This is in the View for Create:
foreach (var cat in #ViewBag.Categories)
{
int idx = 0;
<div class="radio-toolbar">
#foreach (var comp in cat.Components)
{
**<input type="radio" asp-for="#Model.Components.ToList()[idx]" id="#comp.Name" name="#cat.Name" value="#comp"/>
<label for="#comp.Name" asp-for="#Model.ComponenteSistem.ToList()[idx]"> #comp.Name</label>**
}
</div>
idx = idx + 1;
}
It should link every component I choosed with the sistem that I'm currently creating but the relationship table ramains empty:
enter image description here
I think the problem is this part from the label/input : asp-for="#Model.Components.ToList()[idx] but I don't know how to change it to make it work.
Firstly,you cannot bind a whole model to radio button( value="#comp").Here is a working demo for binding Component Id and Name to Sistem:
Category Model:
public class Category {
public List<Component> Components { get; set; }
}
View(change checked radio button and the next hidden input name before form post,so that the selected Id and Name can be binded to Sistem.Components):
<form id="myForm" method="post">
#foreach (var cat in #ViewBag.Categories)
{
<div class="radio-toolbar">
#foreach (var comp in cat.Components)
{
<input type="radio" id="#comp.Id" value="#comp.Id" />
<input hidden id="compName_#comp.Id" value="#comp.Name" />
<label for="#comp.Id"> #comp.Name</label>
}
</div>
}
<button>submit</button>
</form>
<script>
$('#myForm').submit(function () {
var count = 0;
$(".radio-toolbar").each(function () {
$(this).find("input[type='radio']:checked").attr("name", "Components[" + count + "].Id");
$(this).find("input[type='radio']:checked").next().attr("name", "Components[" + count + "].Name");
count++;
})
return true; // return false to cancel form action
});
</script>
Controller(I use fake data to test):
[HttpGet]
public ActionResult Create()
{
Sistem sistem = new Sistem {
Id=1,
Name="sistem1",
Components=new List<Component>
{
new Component{ Id=11, Name=11},
new Component{ Id=12, Name=12},
new Component{ Id=13, Name=13}
}
};
var categories = new List<Category>
{
new Category{ Components=new List<Component>
{
new Component{ Id=11, Name=11},
new Component{ Id=12, Name=12},
new Component{ Id=13, Name=13}
} },
new Category{ Components=new List<Component>
{
new Component{ Id=21, Name=21},
new Component{ Id=22, Name=22},
new Component{ Id=23, Name=23}
} },
new Category{ Components=new List<Component>
{
new Component{ Id=31, Name=31},
new Component{ Id=32, Name=32},
new Component{ Id=33, Name=33}
} }
};
ViewBag.Categories = categories;
return View(sistem);
}
[HttpPost]
public ActionResult Create(Sistem sistem)
{
return Ok();
}
result:

Recursive call of #helper method in ASP.NET MVC Razor, code inside the #helper method is skipped during execution

I am trying to populate the nested Ordered list using #functions & #helper features in ASP.NET MVC Razor.
I am successful in creating nested list using #functions, but when I tried to the same with #helper method execution is not going inside the helper method.
Model:
public class NavigationMenuModels
{
public int ID { get; set; }
public int? ParentID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<NavigationMenuModels> SubNavigationMenu { get; set; }
}
View Model:
public class NavigationMenuViewModel
{
public NavigationMenuViewModel()
{
ListMenu = new List<NavigationMenuModels>();
}
public string ListName { get; set; }
public List<NavigationMenuModels> ListMenu { get; set; }
}
Controller:
public ActionResult NavigationMenu()
{
//Menu
NavigationMenuModels objMenu = new NavigationMenuModels() { ID = 1, ParentID = null, Name = "Menu", Description = "Menu" };
//Menu Items
List<NavigationMenuModels> objMenuItems = new List<NavigationMenuModels>();
objMenuItems.Add(new NavigationMenuModels() { ID = 1, ParentID = 1, Name = "Home", Description = "Home" });
objMenuItems.Add(new NavigationMenuModels() { ID = 2, ParentID = 1, Name = "About", Description = "About" });
objMenuItems.Add(new NavigationMenuModels() { ID = 3, ParentID = 1, Name = "Help", Description = "Help" });
objMenuItems.Add(new NavigationMenuModels() { ID = 4, ParentID = 1, Name = "Contact", Description = "Contact" });
objMenu.SubNavigationMenu = objMenuItems;
//Admin
NavigationMenuModels objAdmin = new NavigationMenuModels() { ID = 2, ParentID = null, Name = "Admin", Description = "Admin" };
//Admin Items
List<NavigationMenuModels> objAdminItems = new List<NavigationMenuModels>();
objAdminItems.Add(new NavigationMenuModels() { ID = 1, ParentID=2, Name = "User Permissions", Description = "User Permissions" });
objAdminItems.Add(new NavigationMenuModels() { ID = 2, ParentID=2, Name = "Security", Description = "Security" });
objAdmin.SubNavigationMenu = objAdminItems;
//Account
NavigationMenuModels objAccount = new NavigationMenuModels() { ID = 3, ParentID = null, Name = "Account", Description = "Account" };
//Account Items
List<NavigationMenuModels> objAccountItems = new List<NavigationMenuModels>();
objAccountItems = null;
objAccount.SubNavigationMenu = objAccountItems;
NavigationMenuViewModel objNavigationMenu = new NavigationMenuViewModel();
objNavigationMenu.ListName = "Master Navigation";
objNavigationMenu.ListMenu.Add(objMenu);
objNavigationMenu.ListMenu.Add(objAdmin);
objNavigationMenu.ListMenu.Add(objAccount);
return View(objNavigationMenu);
}
CSHTML:
#using LearnAngularJs_App1.Models
#using System.Text
#model LearnAngularJs_App1.Models.NavigationMenuViewModel
#{
ViewBag.Title = "NavigationMenu";
}
#functions
{
public static HtmlString GetNestedListHtml(NavigationMenuViewModel Crudeinput)
{
StringBuilder sb = new StringBuilder();
var orderedList = new TagBuilder("ol");
foreach (NavigationMenuModels NavMenu in Crudeinput.ListMenu)
{
var listItem = new TagBuilder("li");
listItem.SetInnerText(NavMenu.Name);
sb.AppendLine(listItem.ToString(TagRenderMode.Normal));
if (NavMenu.SubNavigationMenu != null)
{
if (NavMenu.SubNavigationMenu.Count > 0)
{
sb.AppendLine(BuildNestedList(NavMenu.SubNavigationMenu));
}
}
}
orderedList.InnerHtml = sb.ToString();
return new HtmlString(orderedList.ToString(TagRenderMode.Normal));
}
public static string BuildNestedList(List<NavigationMenuModels> SubMenuList)
{
var sb = new StringBuilder();
var orderedList = new TagBuilder("ol");
if (SubMenuList.Count > 0)
{
foreach (NavigationMenuModels SubNavgationMenuitem in SubMenuList)
{
var listItem = new TagBuilder("li");
listItem.SetInnerText(SubNavgationMenuitem.Name);
sb.AppendLine(listItem.ToString(TagRenderMode.Normal));
if (SubNavgationMenuitem.SubNavigationMenu != null)
{
if (SubNavgationMenuitem.SubNavigationMenu.Count > 0)
{
sb.AppendLine(BuildNestedList(SubNavgationMenuitem.SubNavigationMenu));
}
}
}
}
orderedList.InnerHtml = sb.ToString();
return orderedList.ToString(TagRenderMode.Normal);
}
}
#helper BuildNestedListHelper(List<NavigationMenuModels> Crudeinput)
{
if (Crudeinput.Any())
{
<ol>
#foreach (NavigationMenuModels NavMenu in Crudeinput)
{
<li>
#NavMenu.Name
#if (NavMenu.SubNavigationMenu != null)
{
BuildNestedListHelper(NavMenu.SubNavigationMenu);
}
</li>
}
</ol>
}
}
<h2>NavigationMenu</h2>
<div>
<div><span>Bind Navigation Menu using razor ##funtions</span></div>
<div>
#GetNestedListHtml(Model)
</div>
</div>
<div>
<div><span>Bind Navigation Menu using razor ##helper</span></div>
<div>
#BuildNestedListHelper(Model.ListMenu)
</div>
</div>
When a recursive call to the helper method is made execution is going to the method, but the execution is skipped.
just add "#" in front of the method when recursive call.

three level cascading drop down list

I am a beginner in programming being stuck the last 2 days on that and i am hopping on your help :)
I am building an mvc 4 app and I have a partial view with a list of departments and when you choose the department you can see the item types for this specific department in a drop down list in Browse view.
What I am trying to make is one more dropdown list in Browse view that will show the items according to the selected department and item types.
So this is my code :
View :
#using (Html.BeginForm("Browse", "Bookings", FormMethod.Post, new { id = "TypeItemFormID", data_itemsListAction = #Url.Action("ItemsList") }))
{
<fieldset>
<legend> Type/Item</legend>
#Html.DropDownList("department", ViewBag.ItemTypesList as SelectList, "Select a Type", new {id="ItemTypeID"})
<div id="ItemsDivId">
<label for="Items">Items </label>
<select id="ItemsID" name="Items"></select>
</div>
<p>
<input type ="submit" value="Submit" id="SubmitID" />
</p>
</fieldset>
}
<script src ="#Url.Content("~/Scripts/typeItems.js")"></script>
The controller :
public class BookingsController : Controller
{
private BookingSystemEntities db = new BookingSystemEntities();
//
// GET: /Bookings/
public ActionResult Index()
{
ViewBag.Message = "Select your Department";
var departments = db.Departments.ToList();
return View(departments);
}
public ActionResult Browse(string department, string ID)
{
ViewBag.Message = "Browse for Equipment";
var departments = db.Departments.Include("Items").Single(i => i.DepartmentName == department);
ViewBag.ItemTypesList = GetItemTypeSelectList(department);
return View();
}
public ActionResult Details(int id)
{
var item = db.Items.Find(id);
return View(item);
}
//
// GET: /Home/DepartmentMenu
[ChildActionOnly]
public ActionResult DepartmentMenu()
{
var departments = db.Departments.ToList();
return PartialView(departments);
}
public SelectList GetItemTypeSelectList(string department)
{
var departments = db.Departments.Include("Items").Single(i => i.DepartmentName == department);
List<SelectListItem> listItemTypes = new List<SelectListItem>();
foreach (var item in departments.Items.Select(s => s.ItemType.ItemTypeName).Distinct())
{
listItemTypes.Add(new SelectListItem
{
Text = item,
Value = item,
}
);
}
return new SelectList(listItemTypes.ToArray(),
"Text",
"Value");
}
public ActionResult ItemsList(string ID)
{
string Text = ID;
var items = from s in db.Items
where s.ItemType.ItemTypeName == Text
select s;
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
items.ToArray(),
"ItemId",
"ItemName")
, JsonRequestBehavior.AllowGet);
return RedirectToAction("Browse");
}
}
The Javascript :
$(function () {
$('#ItemsDivId').hide();
$('#SubmitID').hide();
$('#ItemTypeID').change(function () {
var URL = $('#TypeItemFormID').data('itemsListAction');
$.getJSON(URL + '/' + $('#ItemTypeID').val(), function (data) {
var items = '<option>Select a Item</option>';
$.each(data, function (i, item) {
items += "<option value='" + item.Value + "'>" + item.Text + "</option>";
// state.Value cannot contain ' character. We are OK because state.Value = cnt++;
});
$('#ItemsID').html(items);
$('#ItemsDivId').show();
});
});
$('#ItemsID').change(function () {
$('#SubmitID').show();
});
});
And at last my Model :
public class Department
{
public int DepartmentId { get; set; }
[DisplayName("Department")]
public string DepartmentName { get; set; }
public List<Item> Items { get; set; }
}
public class ItemType
{
public int ItemTypeId { get; set; }
[DisplayName("Type")]
public string ItemTypeName { get; set; }
[DisplayName("Image")]
public string ItemTypeImage { get; set; }
public List<Item> Items { get; set; }
}
public class Item
{
public int ItemId { get; set; }
[DisplayName("Name")]
public string ItemName { get; set; }
[DisplayName("Description")]
public string ItemDescription { get; set; }
[DisplayName("Ref Code")]
public string ItemReferenceCode { get; set; }
[ForeignKey("ItemType")]
public int ItemTypeId { get; set; }
public virtual ItemType ItemType { get; set; }
[ForeignKey("Department")]
public int DepartmentId { get; set; }
public Department Department { get; set; }
[DisplayName("Computer Location")]
public string ComputerLocation { get; set; }
[DisplayName("Author Name")]
public string AuthorName { get; set; }
[DisplayName("Published Year")]
public string PublishedYear { get; set; }
}
Here's how I would accomplish something like this. It isn't the only way to do it.
$('#ItemTypeID').on('change', function() {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#ItemTypeID').val() },
success: function(results) {
var options = $('#ItemTypeFormId');
options.empty();
options.append($('<option />').val(null).text("- Select an Item Type -"));
$.each(results, function() {
options.append($('<option />').val(this.ItemTypeFormId).text(this.Value));
});
}
});
});
Then you'd have a controller that looks something like this.
[HttpPost]
public JsonResult GetItemTypeForm(string itemTypeId)
{
//pseudo code
var data = Repostitory.GetData(itemTypeId)
return Json(data);
}

MVC4: View appears to be maintaining state independently of the controller

I have a dropdown (customer) and list of checkboxes (sales orders), dependent upon the currently selected customer. I would expect the checkboxes to clear if I select a new customer, but they are maintained from one to the other, despite the model being cleared in the postback.
I'm not a seasoned MVC developer, but I'm not sure why this should be. When debugging the ViewModel I'm sending back to the view, it is showing IsSelected = false for all the checkboxes, yet in the View, they are selected. What am I doing wrong? (Thanks in advance)
View Model:
namespace MvcTest1.Models
{
public class Customer
{
public int CustomerID { get; set; }
public string Name { get; set; }
}
public class SalesOrder
{
public int SalesOrderID { get; set; }
public string Reference { get; set; }
public bool IsSelected { get; set; }
}
public class SalesOrderPageViewModel
{
public List<Customer> Customers { get; set; }
public int SelectedCustomerID { get; set; }
public List<SalesOrder> SalesOrders { get; set; }
}
}
Controller:
namespace MvcTest1.Controllers
{
public class SalesOrderPageController : Controller
{
[HttpGet]
public ActionResult Index()
{
SalesOrderPageViewModel viewModel = BuildViewModel(1);
return View(viewModel);
}
[HttpPost]
public ActionResult Index(SalesOrderPageViewModel viewModelInput)
{
SalesOrderPageViewModel viewModel = BuildViewModel(viewModelInput.SelectedCustomerID);
return View(viewModel);
}
public SalesOrderPageViewModel BuildViewModel(int customerID)
{
SalesOrderPageViewModel viewModel = new SalesOrderPageViewModel
{
Customers = new List<Customer>
{
new Customer { CustomerID = 1, Name = "Alan" },
new Customer { CustomerID = 2, Name = "Bob" },
new Customer { CustomerID = 3, Name = "Charlie" }
}
};
viewModel.SelectedCustomerID = customerID;
if (customerID == 1)
{
viewModel.SalesOrders = new List<SalesOrder>
{
new SalesOrder { SalesOrderID = 11, Reference = "AA11" },
new SalesOrder { SalesOrderID = 12, Reference = "AA22" },
new SalesOrder { SalesOrderID = 13, Reference = "AA33" }
};
}
if (customerID == 2)
{
viewModel.SalesOrders = new List<SalesOrder>
{
new SalesOrder { SalesOrderID = 21, Reference = "BB11" },
new SalesOrder { SalesOrderID = 22, Reference = "BB22" },
new SalesOrder { SalesOrderID = 23, Reference = "BB33" }
};
}
if (customerID == 3)
{
viewModel.SalesOrders = new List<SalesOrder>
{
new SalesOrder { SalesOrderID = 31, Reference = "CC11" },
new SalesOrder { SalesOrderID = 32, Reference = "CC22" },
new SalesOrder { SalesOrderID = 33, Reference = "CC33" }
};
}
return viewModel;
}
}
}
View:
#model MvcTest1.Models.SalesOrderPageViewModel
#{
ViewBag.Title = "SalesOrderPage";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>SalesOrderPage</h2>
<br /><br />
#using (Html.BeginForm())
{
#Html.DropDownListFor(model =>
model.SelectedCustomerID,
new SelectList(
Model.Customers,
"CustomerID",
"Name",
Model.SelectedCustomerID
),
new { id = "customerSelect" }
);
<script type="text/javascript">
$(function () {
$('#customerSelect').change(function () {
this.form.submit();
});
})
</script>
<br /><br />
for (int i = 0; i < Model.SalesOrders.Count(); i++)
{
#Html.DisplayFor(m => Model.SalesOrders[i].Reference)
#Html.CheckBoxFor(m =>
m.SalesOrders[i].IsSelected
)
<br />
}
}
Looks like Ryan is correct about ModelState.Clear(). Here's an article explaining why it is necessary:
http://patrickdesjardins.com/blog/modelstate-clear-is-required-to-display-back-your-model-object

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

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" />
#foreach (var day in Model.diensten)
{
var currentDay = day;
#Html.DropDownListFor(x => currentDay, new SelectList(ViewBag.Diensten, "Value", "Text"), new { #id = "DienstList" })
}
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" })

Categories

Resources