DropDownList - How to add SelectListItem ASP.NET MVC - c#

I have an DropDownList ,which is showing list of Status,but when i Select an item from DropDownlist and than i Checked HTML Markup i can see there isnt Selected attr and than i researched and find out I need SelectListItem in my Controller and than i tried to implement it in my Controller,but i got some errors :) as usually i implement DropDown in my Razor View (static) , but this time which is first time :) i want implement in my Controller so it becomes dynamic.
Can anyone point me in right direction :)
Thanks in advance :)
Controller:
//DropDown
public List<VMRMA.NameStatusDropDown> GetStatusForDropDown()
{
List<VMRMA.NameStatusDropDown> result = new List<VMRMA.NameStatusDropDown>();
var obj = db.RMAStatus.Select(u => u).ToList();
if (obj != null && obj.Count() > 0)
{
foreach (var data in obj)
{
VMRMA.NameStatusDropDown model = new VMRMA.NameStatusDropDown();
model.Status = data.Status;
model.ID = data.ID;
result.Add(model);
}
}
return result;
}
//Dropdown runs in this Action
public ActionResult RMA ()
{
VMRMA model = new VMRMA();
model.NameStatusDropDowns = GetStatusForDropDown();
//RMA query and some an other stuff
return View(model);
}
ViewModel:
public class VMRMA
{
public List<NameStatusDropDown> NameStatusDropDowns { get; set; }
//DropDown
public class NameStatusDropDown
{
public NameStatusDropDown()
{
}
public NameStatusDropDown(int ID, string Status)
{
this.ID = ID;
this.Status = Status;
}
public int ID { get; set; }
public string Status { get; set; }
}
}
View:
#using ModelNamespace.Models
#model VMRMA
<form>
<div class="form-group">
<label class="form-control-label">Select a status</label>
<br />
<select>
<option>Select</option>
#foreach (var item in Model.NameStatusDropDowns)
{
<option value="#item.ID">#item.Status</option>
}
</select>
</div>
<div class="form-group">
<input type="submit" value="Send data" class="btn btn-primary">
</div>
</form>
HTML Markup:
<div class="form-group">
<label class="form-control-label">Select a status</label>
<br>
<select>
<option>Select</option>
<option value="1">Sendt</option>
<option value="2">Under behandling</option>
<option value="3">Blive behandlet</option>
<option value="4">Modtaget</option>
</select>
</div>

This two Post helped me out to solve the problem and Thanks to #Stephen Muecke with his good post, Which is wroted Here and Thanks to this post with great explanation, which is wroted Here.
Here is what i did , maybe it helped someone one day :) :
Add To Property to my View Model :
public class VMRMA
{
public List<SelectListItem> Status { set; get; }
public int? SelectedStatus { set; get; }
}
Change my ActionResult to :
public ActionResult RMA (int Id)
{
VMRMA model = new VMRMA();
model.Status = new SelectList(DatabaseNameSpace.RMAStatus, "ID",
"Status").ToList();
//some an other stuff
return View(model);
}
and than change my View to :
#Html.DropDownListFor(s => s.SelectedStatus, Model.Status, "- Select -", new { #class = "form-control" })

Controller:
ViewBag.Statuses= new SelectList(_context.RMAStatus
.Select(item => new { value = item.Id, text = item.Status}), "value", "text", selectedId);
View:
#Html.DropDownListFor(x => x.StatusId, ViewBag.Statuses as SelectList, "- please select -")

Create a partial view as this:
#model MyApp.Models.MyClass
#{
Layout = null;
}
#*#Html.Partial("ActionMethod", "Controller", new ViewDataDictionary { { "Name", "TestName" } })*#
#Html.DropDownList((String)TempData["Name"], new SelectList( ViewBag.Specialities,"Value","Text"),
new { #class = "form-control", #multiple="multiple" });
Then in your controller
List<MyClass> lstSpecialities =
ViewBag.Specialities = lstSpecialities; // Now it is available for the view
Last step, load your view using #Html.RenderAction()

Related

Error in related DropDownList's when page refreshes

I have two related ddl's. When page loads, I can POST them to controller and everything is ok. But also I have some fields in page, and if they are empy I call ModalError in my controller, then page should be reloaded with text of errors. But it throughs an error, that says IEnumerable<SelectList> with name City is empty. What is the problem?
View:
#using (#Html.BeginForm())
{
<div>
#Html.LabelFor(model=>model.Buyer.buyers_name)
</div>
<div>
#Html.EditorFor(model=>model.Buyer.buyers_name)
#Html.ValidationMessageFor(model=>model.Buyer.buyers_name)
</div>
<div>
#Html.LabelFor(model=>model.Buyer.buyers_email)
</div>
<div>
#Html.EditorFor(model=>model.Buyer.buyers_email)
#Html.ValidationMessageFor(model=>model.Buyer.buyers_email)
</div>
<div>
#Html.LabelFor(model=>model.Buyer.buyers_phone)
</div>
<div>
#Html.EditorFor(model=>model.Buyer.buyers_phone)
#Html.ValidationMessageFor(model=>model.Buyer.buyers_phone)
</div>
<div>
<h2>Выберите адрес доставки:</h2>
<h3>Выберите город</h3>
#Html.DropDownList("City", ViewBag.cities as SelectList, new { id = "city" })
<h3>Выберите адрес</h3>
#Html.DropDownList("Address", ViewBag.addresses as SelectList, new { id = "address" })
</div>
<input type="submit" value="Send" class="btn" />
}
Controller:
public ActionResult GetItems(decimal id)
{
return PartialView(_db.bs_delivery_type.Where(x => x.delivery_city_id == id).ToList());
}
public ActionResult Checkout()
{
int selectedIndex = 1;
SelectList cities = new SelectList(_db.bs_cities, "cities_id", "cities_name", selectedIndex);
ViewBag.cities = cities;
SelectList addresses = new SelectList(_db.bs_delivery_type.Where(x => x.delivery_city_id == selectedIndex), "delivery_id", "delivery_address");
ViewBag.addresses = addresses;
return View();
}
[HttpPost]
public ActionResult Checkout(Cart cart, DeliveryModel deliveryModel, decimal city, decimal address)
{
if (cart.Lines.Count() == 0)
{
ModelState.AddModelError("", "Your cart is empty");
}
if (ModelState.IsValid)
{
//adds to db;
return View("Completed");
}
else
{
return View(deliveryModel);
}
}
DeliveryModel:
public class DeliveryModel
{
public bs_buyers Buyer { get; set; }
public List<bs_cities> CitiesModel { get; set; }
public SelectList FilteredDelivery { get; set; }
}
Also PartialView GetItems:
<select id="address" name="Address">
#foreach (var item in Model)
{
<option value="#item.delivery_id">#item.delivery_address</option>
}
As you invoke the Checkout Action in your Controller via HttpPost you then return the Checkout View in case the ModelState is invalid. However you do net set your ViewBag Variables as you do in your HttpGet Action.
You have to set ViewBag Variables in each and every Action. In this case I would recommend a separate method that gets invoked in both Actions.
private void SetViewBagForCheckout(){
int selectedIndex = 1;
SelectList cities = new SelectList(_db.bs_cities, "cities_id", "cities_name", selectedIndex);
ViewBag.cities = cities;
SelectList addresses = new SelectList(_db.bs_delivery_type.Where(x => x.delivery_city_id == selectedIndex), "delivery_id", "delivery_address");
ViewBag.addresses = addresses;
}

Bind multiple values to a single checkbox and post it to controller

Model.cs
A campaign can have multiple images, that's why IEnumerable<int> ImageIdList.
public class Campaign
{
public int Id { get; set; }
public int CreatedBy { get; set; }
public int UpdatedBy { get; set; }
public IEnumerable<int> ImageIdList { get; set; }
}
View.cshtml
I want to download all the images related to a campaign, based on the ImageIdList, that's why I need to post all these ImageIds when a particular Campaign is checked and download button is clicked.
#model Campaign
#{
Layout = "....";
var assets = Model.AssetsInCampaign.ToList();
}
#using (Html.BeginForm("action-method", "controller", FormMethod.Post))
{
<div class="btnSubmit">
<input type="submit" value="Download Asset(s)" />
</div>
#foreach(var i in assets)
{
<div class="s_checkcol">
<input type="checkbox" name="ids" />
#foreach (var imageId in i.Where(c => c.AssetId == doc.FileDataId).SelectMany(c => c.ImageIdList))
{
<input type="hidden" name="ids" value=#(imageId)>
}
</div>
}
}
Controller.cs
public ActionResult DownloadFiles(IEnumerable<int> ids)
{
// code
}
NOTE: Only a part of code(where I'm facing the problem) is provided here. Its a DB first approach and in no way I can alter that (ORDERS).
I tried the above, but all of the ids are posted to the controller no matter how many checkboxes are selected.
Question: How should I bind the IEnumerable<int> ImageIdList property to a checkbox in View.cs and post the data to Controller.cs so that only the ids of selected checkboxes are posted?
This is a nice practice... it will work and Iam working with such a
manner (Iam sure that it will work very well) but one thing you have to be very carefull while coding this, little bit
complicated
Iam taking this effort not only for as an answer to this particular question.
Its for all stackoverflow users. Because i never found the below method anyware in stackoverflow.
I get this method by a long search. You people can use this.
It will help you to avoid for loops to bind the Checkboxlist
Its the best good for re-usability (need a single line (max: 20-25 chars to bind a CheckBoxList in Razor))
CheckBoxListItem.cs
create a New Class CheckBoxListItem //you can use any other names
public class CheckBoxListItem
{
public int ID { get; set; }
public string Display { get; set; }
public bool IsChecked { get; set; }
}
MyModel.cs
This is modelclass
public class MyModel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<CheckBoxListItem> ChkList { get; set; }
}
HomeController.cs
This is controller
public ActionResult Index()
{
var model = new MyModel(){
Id = 0,
Name = "Your Name",
ChkList = dbContext.myTable.Select(x => new CheckBoxListItem { ID = x.MyTableFieldID, Display = x.MyTableFieldName, IsChecked = true })
//If you need only int part, then just avoid to bind data on Display field
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyModel myModel) //Your model object on PostAction
{
IEnumerable<CheckBoxListItem> ChkList = myModel.ChkList;
// Here is your answer, You can see all your check box items (both checked and unchecked) in ChkList, it will shows all your checked items are true and non-checked items are false in IsChecked field
}
Here you have to give more patiance
Goto the Folder View>Shared>EditorTemplates and RightClick Add>View... and Create a new View with the same name CheckBoxListItem.cshtml
CheckBoxListItem.cshtml
#model Project.Models.CheckBoxListItem
<div class="">
#Html.HiddenFor(x => x.ID)
<div class="">
#Html.CheckBoxFor(x => x.IsChecked)
</div>
#Html.LabelFor(x => x.IsChecked, Model.Display, new { #class = "" })
</div>
Create your View
Index.cshtml
#model #model Project.Models.MyModel
<div class="form-group">
#Html.LabelFor(model => model.Id, htmlAttributes: new { #class = "" })
<div class="col-md-10">
#Html.EditorFor(model => model.Id, new { htmlAttributes = new { #class = "" } })
#Html.ValidationMessageFor(model => model.Id, "", new { #class = "" })
</div>
</div>
#Html.EditorFor(model => model.ChkList) //This only one line of code is enough to bind a checkBoxList in future
<input type="submit" value="Create" class="" />
You will get all these in your post action

SelectListItem not Returning Results - MVC5

I have tried a multitude of different posts and tags and mixtures and not getting a return of data on my select lists. I have even ready that some people have to use jquery to highlight the lists before sending them; This is incredibly doable IF selecting the item actually passed the item! I am willing to use Jquery, I am willing to update the model, I am willing to do whatever it takes to get the model data BACK, but it seems all of those return count=0 or null.
I am using 2 list boxes with some movement inside of them and want to return the contents of both listboxes upon completion.
(If there is another way to be doing this, please share!)
Model:
public class RoleAddRemoveListBoxViewModel
{
public List<System.Web.Mvc.SelectListItem> CurrentRoles { get; set; }
public List<System.Web.Mvc.SelectListItem> NonMemberRoles { get; set; }
}
Controller:
[HttpPost]
public ActionResult ManageUserRoles(string userList)
{
List<SelectListItem> lbMemberRoles = new List<SelectListItem>();
List<SelectListItem> lbNonMemberRoles = new List<SelectListItem>();
var user = (from u in db.Users
where u.UserName == userList
select u).SingleOrDefault();
// prepopulate roles for the view dropdown
var roleList = db.Roles.OrderBy(r => r.Name).ToList().Select(rr =>
new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
var userRoles = UserManager.GetRoles(user.Id);
foreach (var role in roleList)
{
if (userRoles.Contains(role.Value.ToString()))
{
lbMemberRoles.Add(role);
}
else
{
lbNonMemberRoles.Add(role);
}
}
RoleAddRemoveListBoxViewModel lbvm = new RoleAddRemoveListBoxViewModel
{
CurrentRoles = lbMemberRoles,
NonMemberRoles = lbNonMemberRoles
};
return View(lbvm);
}
[HttpPost]
public ActionResult UpdateUserRoles(RoleAddRemoveListBoxViewModel model)
{
TempData["updateState"] = "User Role Updated Successfully!";
return RedirectToAction("Index");
}
View:
#model WebDocEditor.Models.RoleAddRemoveListBoxViewModel
#{
using (Html.BeginForm("UpdateUserRoles", "Roles", FormMethod.Post))
{
<body>
<fieldset>
<form>
<div class="row">
<div class="col-xs-2">
#Html.LabelFor(model => model.CurrentRoles)
<div>
#Html.ListBoxFor(model => model.CurrentRoles, Model.CurrentRoles)
</div>
</div>
<div class="btn-group-vertical col-xs-1">
<div id="moveRightbtn" class="btn glyphicon glyphicon-arrow-right"></div>
<div id="moveLeftbtn" class="btn glyphicon glyphicon-arrow-left"></div>
</div>
<div class="col-xs-2">
#Html.LabelFor(model => model.NonMemberRoles)
<div>
#Html.ListBoxFor(model => model.NonMemberRoles, Model.NonMemberRoles)
</div>
</div>
</div>
<input type="submit" value="Save" />
</form>
</fieldset>
</body>
}
}
After action edit: I Wanted to throw in the JQuery I used for the highlighting since I see so many threads on how THEY got it to work and wanted to show what worked with my combination/setup:
JS on View:
#section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
$('#moveRightbtn').on('click', function () {
var selectedCurrent = $('#CurrentRoles option:selected');
$('#NonMemberRoles').append($(selectedCurrent).clone());
$(selectedCurrent).remove()
//alert(selectedCurrent);
})
$('#moveLeftbtn').on('click', function () {
var selectedNonMember = $('#NonMemberRoles option:selected');
$('#CurrentRoles').append($(selectedNonMember).clone());
$(selectedNonMember).remove()
//alert(selectedNonMember);
})
$("#submitBtn").on('click', function (e) {
$("#CurrentRoles option").prop('selected', 'selected');
$("#NonMemberRoles option").prop('selected', 'selected');
});
});
</script>
}
Your lists needs to be separate from what you're returning.. you should set your model up like this.
public class RoleAddRemoveListBoxViewModel
{
public List<System.Web.Mvc.SelectListItem> CurrentRolesList { get; set; }
public List<System.Web.Mvc.SelectListItem> NonMemberRolesList { get; set; }
public string[] CurrentRoles {get;set;}
public string[] NonMemberRoles {get;set;}
}
List boxes will return an array of whatever is selected.. In this case you can just set the properties to string[]
In your view, use the new properties as the expression and the List properties as the selectList
#using (Html.BeginForm())
{
<div class="row">
<div class="col-xs-2">
#Html.LabelFor(model => model.CurrentRoles)
<div>
#Html.ListBoxFor(model => model.CurrentRoles, Model.CurrentRolesList)
</div>
</div>
<div class="btn-group-vertical col-xs-1">
<div id="moveRightbtn" class="btn glyphicon glyphicon-arrow-right"></div>
<div id="moveLeftbtn" class="btn glyphicon glyphicon-arrow-left"></div>
</div>
<div class="col-xs-2">
#Html.LabelFor(model => model.NonMemberRoles)
<div>
#Html.ListBoxFor(model => model.NonMemberRoles, Model.NonMemberRolesList)
</div>
</div>
</div>
<input type="submit" value="Save" />
}
in your controller.. make sure you set the right properties to your lists
public ActionResult ManageUserRoles(string userList)
{
List<SelectListItem> lbMemberRoles = new List<SelectListItem>();
List<SelectListItem> lbNonMemberRoles = new List<SelectListItem>();
var user = (from u in db.Users
where u.UserName == userList
select u).SingleOrDefault();
// prepopulate roles for the view dropdown
var roleList = db.Roles.OrderBy(r => r.Name).ToList().Select(rr =>
new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
var userRoles = UserManager.GetRoles(user.Id);
foreach (var role in roleList)
{
if (userRoles.Contains(role.Value.ToString()))
{
lbMemberRoles.Add(role);
}
else
{
lbNonMemberRoles.Add(role);
}
}
RoleAddRemoveListBoxViewModel lbvm = new RoleAddRemoveListBoxViewModel
{
CurrentRolesList = lbMemberRoles,
NonMemberRolesList = lbNonMemberRoles
};
return View(lbvm);
}
not sure why you had this actionresult as a [HttpPost] but you might want to remove that attribute..
the way list boxes work, it will only post back what is actually selected.. so you might have to select all of the items in each list if you want to return all of the values in them
Add string[] for your return properties.
public List<System.Web.Mvc.SelectListItem> CurrentRoles { get; set; }
public List<System.Web.Mvc.SelectListItem> NonMemberRoles { get; set; }
public string[] SelectedCurrentRoles{ get; set; }
public string[] SelectedNonMemberRoles{ get; set; }
and use MultiSelectList in your ListBoxFor. I would use a different model to pass in but you could use your existing List<SelectListItem>
#Html.ListBoxFor(model => model.SelectedCurrentRoles, new MultiSelectList(Model.CurrentRoles, "Value", "Text"))
#Html.ListBoxFor(model => model.SelectedNonMemberRoles, new MultiSelectList(Model.NonMemberRoles , "Value", "Text"))

How to insert dynamically generated dropdownlist value into DB by using MVC

Need help in MVC : Please help in Creating dropdownlist(child) based on the count from a dropdownlist selected value(integer)- consider it as a parent control. And insert the child dropdownlist selected values to the database using MVC Eg; If 3 is selected in parent dropdownlist,3 new dropdownlist needs to be created and selected values of 3 dropdownlist needs to be inserted into DB--By using MVC dropdownlist . While I tried,only first child dropdownlist selected value is getting inserted or three times..Please help in resolving it
First Creating parent dropdownlist. Starting with Home Controller, i create a list
public ActionResult Index()
{
List<int> key =new List<int>();
key.Add(1); key.Add(2); key.Add(3); key.Add(4); key.Add(5);
ViewBag.RequiredKey = new SelectList(key);
return View();
}
In the Index View i show the parent dropdownlist
#using (Html.BeginForm("SelectedDropDownResult", "Home",FormMethod.Post))
{
#Html.DropDownList("SelectedDropDownValue", (SelectList)ViewBag.RequiredKey, new { #class = "form-control" })
<input type="submit" value="Submit">
}
Here in this dropdownlist user selects a value which is posted to the action named SelectedDropDownResult in the Home controller
public ActionResult SelectedDropDownResult(FormCollection fc)
{
int dropDown = int.Parse(fc["SelectedDropDownValue"]);
ViewBag.dropDownValue = dropDown;
List<int> key = new List<int>();
key.Add(1); key.Add(2); key.Add(3); key.Add(4); key.Add(5);
ViewBag.RequiredKey = new SelectList(key);
return View();
}
Using FormCollection lets extract the user selected value in parent drop down
#{
ViewBag.Title = "SelectedDropDownResult";
}
<h3> Generating #ViewBag.dropDownValue based on parent drop down selected value</h3>
#using (Html.BeginForm("ChildDropDown", "Home", FormMethod.Post))
{
<input type="hidden" name="childDropDownValue" value=#ViewBag.dropDownValue>
for (int i=0; i< #ViewBag.dropDownValue;i++ )
{
#Html.DropDownList("SelectedDropDownValue"+i, (SelectList)ViewBag.RequiredKey, new { #class = "form-control" })
}
<input type="submit" value="Submit">
}
Here child drop down lists are created based on the count of parent list and action ChildDropDown is called to save data to database
public ActionResult ChildDropDown(FormCollection fc)
{
List<int> child=new List<int>();
int dropDown = int.Parse(fc["childDropDownValue"]);
for(int i=0;i<dropDown;i++)
{
child.Add(int.Parse(fc["SelectedDropDownValue"+i]));
}
// code to add data child list to the database
return View();
}
}
You can now add code to save data to the database in ChildDropDown action of Home controller
A sample how you can hold your child Dropdowns value.
ViewModels-
public class TestModelViewModel
{
public int ParentId { get; set; }
public IEnumerable<ParentListViewModel> ParentList { get; set; }
public int ChildId { get; set; }
public IEnumerable<ParentListViewModel> ChildList { get; set; }
public IEnumerable<int> ChildIds { get; set; }
}
public class ParentListViewModel
{
public int Id { get; set; }
public string Value { get; set; }
}
public class ChildListViewModel
{
public int ChildId { get; set; }
public string ChildValue { get; set; }
}
Controller-
public ActionResult Index()
{
var model = new TestModelViewModel
{
ParentList = new List<ParentListViewModel>
{
new ParentListViewModel{
Id = 1,
Value = "One"
},new ParentListViewModel{
Id = 2,
Value = "Two"
},new ParentListViewModel{
Id = 3,
Value = "Three"
},
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(TestModelViewModel model)
{
var ChildIds = model.ChildIds;
/* now you can save these ChildIds to your db */
return View(model);
}
View-
#model WebApplication1.Models.TestModel
#{
ViewBag.Title = "Home Page";
}
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { area=""}))
{
<div class="row">
<div class="col-md-12">
<h2>Parent List</h2>
<p>
<select id="ParentList" name="ParentId">
<option value="">--- select parent list ---</option>
#foreach (var item in Model.ParentList)
{
<option value="#item.Id">#item.Value</option>
}
</select>
</p>
</div>
<div class="col-md-12">
<h2>Child List</h2>
<p id="childListCotnainer">
</p>
</div>
<div class="col-lg-12"><input class="btn btn-default" type="submit" value="submit" /> </div>
</div>
}
#section scripts{
<script>
$(function () {
$("#ParentList").change(function () {
var length = parseInt($(this).val());
var dropHtml = '';
for (i = 0; i < length; i++) {
dropHtml += '<select name="ChildIds"><option value="1">Child One</option><option value="2">Child Two</option><option value="3">Child Three</option></select><br /><br />';
}
$("#childListCotnainer").html(dropHtml);
});
});
</script>
}

MVC4 DropDownList from DB

I'm trying to make very simple forum, but I have problem with DropDownList. I have two models:
ForumThread.cs
public partial class ForumThread
{
public ForumThread()
{
this.ForumCategory = new HashSet<ForumCategory>();
}
public int TH_ID { get; set; }
public System.DateTime DATE { get; set; }
public string TOPIC { get; set; }
public string USER { get; set; }
public virtual ICollection<ForumCategory> ForumCategory { get; set; }
}
ForumCategory.cs
public partial class ForumCategory
{
public ForumCategory()
{
this.ForumThread = new HashSet<ForumThread>();
}
public int CA_ID { get; set; }
public string CATEGORY { get; set; }
public bool isSelected { get; set; }
public virtual ICollection<ForumThread> ForumThread { get; set; }
}
I tried to make "Create" function with view:
Create
#model AnimeWeb.Models.ForumThread
#{
ViewBag.Title = "Create";
}
<h2>New Thread</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<div class="editor-field">
#Html.HiddenFor(model => model.TH_ID)
</div>
<div class="editor-label">
TOPIC
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TOPIC)
#Html.ValidationMessageFor(model => model.TOPIC)
</div>
<div class="editor-label">
CATEGORY
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ForumCategory)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
And PartialView for ForumCategory:
ForumCategory
#model AnimeWeb.Models.FORUMCATEGORY
#Html.HiddenFor(model => model.CA_ID)
#Html.HiddenFor(model => model.CATEGORY)
<div>
#Html.DropDownListFor(item => Model.CA_ID, ViewBag.CA_ID as SelectList, "-- Select --")
</div>
ForumController
public ActionResult Create()
{
var db = new MainDatabaseEntities();
var viewModel = new ForumThread
{
ForumCategory = db.ForumCategory.Select(c => new { CA_ID = c.CA_ID, CATEGORY = c.CATEGORY, isSelected = false }).ToList().Select(g => new ForumCategory
{
CA_ID = g.CA_ID,
CATEGORY = g.CATEGORY,
isSelected = false
}).ToList(),
};
return View(viewModel);
}
//
// POST: /Forum/Create
[HttpPost]
public ActionResult Create(ForumThread forumthread, String user, int id)
{
var db = new MainDatabaseEntities();
var newthread = new ForumThread
{
TH_ID = forumthread.TH_ID,
DATE = DateTime.Now,
TOPIC = forumthread.TOPIC,
USER = forumthread.USER,
ForumCategory = new List<ForumCategory>()
};
foreach (var selectedCategory in forumthread.FORUMCATEGORY.Where(c => c.isSelected))
{
var category = new ForumCategory { CA_ID = selectedCategory.CA_ID };
db.ForumCategory.Attach(category);
newthread.ForumCategory.Add(category);
}
db.ForumThread.Add(newthread);
db.SaveChanges();
return RedirectToAction("Index");
}
And it obviously doesn't work. I tried to use other threads on this forum but nothing helped. Could someone explain me how to make this work?
The error is in partial view of ForumCategory:
The ViewData item that has the key 'CA_ID' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
In your PartialView for ForumCategory, your cast is not correct:
#Html.DropDownListFor(item => Model.CA_ID, ViewBag.CA_ID as SelectList, "-- Select --")
You have to use a SelectList (List of SelectListItem) that you can implement for example in a method in your model:
public List<SelectListItem> GetCategories()
{
var db = new MainDatabaseEntities();
List<SelectListItem> list = new List<SelectListItem>();
// Add empty item if needed
SelectListItem commonItem = new SelectListItem();
commonItem.Text = "--- Select ---";
commonItem.Value = "-1";
commonItem.Selected = true;
list.Add(commonItem);
// Add items from Database
foreach (ForumCategory fc in db.ForumCategory)
{
SelectListItem i = new SelectListItem();
i.Text = fc.CATEGORY;
i.Value = fc.CA_ID.ToString();
list.Add(i);
}
return list;
}
And then you can have you dropdown like that:
#Html.DropDownList("DropName", Model.GetCategories())
There may be other errors in some parts of your code, I just answered to the one you quoted
In your editortemplate, you have:
ViewBag.CA_ID as SelectList
But you don't show where you fill the ViewBag. Instead you might want to do something like this:
#Html.DropDownListFor(m => m.CA_ID,
new SelectList(Model.ForumCategory,
"CA_ID", "CATEGORY", Model.CA_ID))
As also explained in MVC3 DropDownListFor - a simple example?.

Categories