Populate Data in DropDownList in Create Mode MVC 4 - c#

I'm trying to populate data from table in DropDownList using MVC4. Trying to figure it out how to get all the languages' titles into the DropDown in the Edit mode.
Models:
public class CategoryLanguage
{
public int ID { get; set; }
public int LanguageID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
}
public class Language
{
public int ID { get; set; }
public string Title { get; set; }
}
Controller:
public ActionResult Create()
{
using (MyDBContext db = new MyDBContext())
{
ViewBag.ID = new SelectList(db.Languages, "ID", "Title");
return View();
}
}
//
// POST: /Emp/Create
[HttpPost]
public ActionResult Create(CategoryLanguage newCatLang)
{
using (MyDBContext db = new MyDBContext())
{
if (ModelState.IsValid)
{
db.CategoryLanguages.Add(newCatLang);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ID = new SelectList(db.Languages, "ID", "Title", newCatLang.LanguageID);
return View(newCatLang);
}
}
View:
#model MultilanguageCategories.CORE.Models.CategoryLanguage
#{
ViewBag.Title = "Create";
}
<h2>Add New Item</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#Html.DropDownList("ID", "--Select--")
}
Trying to figure it out how to get all the languages' titles into the DropDown when creating new CategoryLanguage entity. The error says: "The operation cannot be completed because the DbContext has been disposed." and this line marked: #Html.DropDownList("ID", "--Select--")

Change your get method "Create" as mentioned below :
public ActionResult Create()
{
var languages = new List<Language>();
using (MyDBContext db = new MyDBContext())
{
languages = db.Languages.ToList();
}
ViewBag.ID = new SelectList(languages, "ID", "Title");
return View();
}
Now you can use DropDownListFor as mentioned below :
#Html.DropDownListFor(model => model.[PropertyName], (IEnumerable<SelectListItem>)ViewBag.ID)

you're close...
You need to Add the languages select list to the viewbag (which you've already done, but with a badly named key)
ie: ViewBag.LanguagesList = new SelectList(db.Languages, "ID", "Title");
if you want an empty field that's easy enough too:
var langs = db.Languages.ToList().ConvertAll(x => new SelectListItem() { Value = x.ID, Text = x.Title });
langs.Insert(0, new SelectListItem() { Value = "", Text = "--Select--" });
ViewBag.LanguagesList = langs;
The DropdownList should be for a property in the model.
#Html.DropDownListFor(m => m.LanguageID, (IEnumerable<SelectListItem>)ViewBag.LanguagesList)
As it looks like you are using an Entity Framework class as your model you need to ensure the context is not disposed before the view is rendered.
As Per Microsoft's example link instantiate the context at the top of the controller, and drop the using statement in the Create method.
ie :
public class LanguageCategoryController : Controller
{
MyDBContext db = new MyDBContext();
public ActionResult Create()
{
ViewBag.LanguagesList = new SelectList(db.Languages, "ID", "Title");
// or replace the above line with the other example above
// if you want the empty "--select--" option
return View();
}
}

Related

DropdownListFor doesn't show the selected value

I am so confused how to make the dropdownlist to show the selected value.
Model:
public class SampleModel
{
public string State { get; set; }
}
Controller:
public ActionResult EditInformation()
{
ViewBag.State = new SelectList(db.States, "StateName", "StateName");
string userEmail = User.Identity.GetUserName();
Sample model = new SampleModel();
model.State = "Melbourne";
return View(model);
}
View :
#Html.DropdownListFor(m => m.State, ViewBag.State as IEnumerable<SelectListItem>, "-- Select State --")
The list is showing the states just fine, but it doesn't automatically select the value I assigned ("Melbourne"). I have tried using the selectlist constructor to assign the selectedValue, but after doing a lot of research, someone wrote that it is redundant to use the selectlist constructor if you are using Html.DropdownListFor() since you will be using the value assigned to the model.
EDIT:
Here is my db.State model:
public class State
{
[Key]
public int StateId { get; set; }
public string StateName { get; set; }
}
Again to clarify, I want to use StateName as the value and the text for the selectlistitem.
EDIT:
My full action method:
public ActionResult EditInformation()
{
//var states = ndb.States.Select(s => new SelectListItem { Text = s.StateName, Value = s.StateName , Selected = s.StateName == "Jawa Timur" }).ToList();
ViewBag.State = new SelectList(ndb.States, "StateName", "StateName");
ViewBag.City = new SelectList(ndb.Cities, "CityName", "CityName");
string[] countries = { "Indonesia" };
ViewBag.Country = new SelectList(countries);
string userEmail = User.Identity.GetUserName();
try
{
UserInformation userInfo = ndb.UserInformations.Single(m => m.Email == userEmail);
UserAccountViewModel model = new UserAccountViewModel();
model.Address = userInfo.Address;
model.Email = userEmail;
model.FirstName = userInfo.FirstName;
model.LastName = userInfo.LastName;
model.Phone = userInfo.Phone;
model.PostalCode = userInfo.PostalCode;
Debug.Print(userInfo.State);
model.State = userInfo.State;
model.City = userInfo.City;
model.Country = userInfo.Country;
return View(model);
}catch { }
return View();
}
public ActionResult EditInformation(int? id /*this will be passed from your route values in your view*/)
{
State myState = db.States.Find(id)
ViewBag.State = new SelectList(ndb.States, "StateId", "StateName", myState.StateId);
}//I only added this because this is what the question pertains to.
In your EditInformation View you need to have an actionlink to link to the user's id so that you pull up the right information, so:
EditInformation View:
#foreach (var item in Model)
{
#Html.ActionLink("Edit Information", "EditInformation", /*Controller Name if this view is rendered from a different controller*/, new { id = item.id })
}
try this:
public class SampleModel
{
public int Id { get; set; }
public string State { get; set; }
}
Controller:
public ActionResult EditInformation()
{
//Select default value like this (of course if your db.States have an Id):
ViewBag.State = new SelectList(db.States, "Id", "StateName", 1 /*Default Value Id or Text*/);
. . .
return View();
}
SelectList(IEnumerable, String, String, Object) - Initializes a new instance of the SelectList class by using the specified items for the list, the data value field, the data text field, and a selected value.
View:
#Html.DropdownList("State", null, "-- Select State --")
Or Like you do:
#Html.DropdownListFor(m => m.State, ViewBag.State as IEnumerable<SelectListItem>, "-- Select State --")
UPDATE:
You can get Selected text using jQuery like so:
Add #Html.HiddenFor(x => x.State)
#Html.DropdownListFor(m => m.State, ViewBag.State as IEnumerable<SelectListItem>, "-- Select State --", new { id = "stateId" })
#Html.HiddenFor(x => x.State)
JS:
$(function () {
$("form").submit(function(){
var selectedText= $("#stateId :selected").text();
$("#State").val(selTypeText);
});
});
Post:
[HttpPost]
public void UploadDocument(State model)
{
if(ModelState.IsValid)
{
string state = model.State;
}
}
OKAY, So after researching for quite some time, the problem lies in the naming convention. Apparently, you cannot use ViewBag.State for Html.DropdownListFor(m => m.State), this somehow causes the Html.DropdownListFor(m => m.State) to not reading the data properly.

Dropdownlist issue in razor

hi all i have a controller
public ActionResult Search(FormCollection collection)
{
....
var column = new Models.ColumnMapping("CTR");
ViewData["ColoumName"] = column;
var search = new Models.Search(columnname,searchvalue);
return View(search);
}
my view data contains following model property value..
public class Column {
public string ColumnName { get; set; }
public DataTypes DataType { get; set; }
}
i have to create a drop down list for ColumnName(all data contain in VIewData) and my view is like
#Html.DropDownListFor("clname", ViewData["ColoumName"] as IEnumerable<AML.Web.Models.Column>, "ColumnName", "ColumnName"))
but this is not working
Try like this, This is just an example.
View
#Html.DropDownList("CustomerId", (SelectList)ViewBag.CustomerNameID, "--Select--")
Controller
public ActionResult CustomerInfo()
{
ViewBag.CustomerNameID = new SelectList(new[]
{
new {ID="1",Name="name1"},
new{ID="2",Name="name2"},
new{ID="3",Name="name3"},
},"ID", "Name");
return View();
}
Model
public Class ViewModel {
public int CustomerId { get; set; }
}
If you have to use #Html.DropDownListFor then it should like this #Html.DropDownListFor(m => m.CustomerId ,(List<SelectList>)ViewBag.CustomerNameID,"-- Select --", new { #class = "input-block-level" })
instead of DropDownListFor try DropDownList with SelectList().
#Html.DropDownList("clname",
new SelectList((IEnumerable) ViewData["ColoumName"], "Id", "ColoumName"))

Displaying multiple tables from model in single view

I have two tables TxtComment and Login.
I am displaying image urls from Login table and comments from TxtComment table where username in TxtComment equals username in Login.
I am using Db First approach using entityframework.
How can I concatenate these columns from different tables to one common view? I used ViewBag. I got a result.
Controller
public ActionResult Item(int id)
{
FoodContext db = new FoodContext();
ViewBag.FoodItems = db.FoodItems.Where(row => row.itemid == id);
ViewBag.TxtComments = (from user in db.TxtComments
from ff in db.Logins
where ff.username == user.username
select new { imgurl = ff.imgurl, txtcmt = user.txtcmt });
return View();
}
View
#for(var item in ViewBag.TxtComments)
{
<div>#item</div>
}
The result is {imgurl=http:/sdfsdf,txtcmt=sfsdfsdf}
I need each item seperate. How can I? I tried with #item.imgurl, it says error. Is view bag is better? If not, please help me this need with strongly type view.
Create your own ViewModel instead of putting the model inside the ViewBag.
ViewModel:
public class ViewModel
{
public List<ImageComment> ImageComments { get; set; }
public ViewModel()
{
ImageComments = new List<ImageComment>();
}
}
public class ImageComment
{
public string ImageUrl { get; set; }
public string Comment { get; set; }
}
Controller Action:
public ViewResult Item(int id)
{
FoodContext db = new FoodContext();
List<ImageComment> comments = (from user in db.TxtComments
from ff in db.Logins
where ff.username == user.username
select new ImageComment
{
ImageUrl = ff.imgurl,
Comment = user.txtcmt
}).ToList();
ViewModel vm = new ViewModel{ ImageComments = comments };
return View("MyView", vm);
}
View:
#model ViewModel
#{
ViewBag.Title = "Comments";
}
#foreach(ImageComment comment in Model.ImageComments)
{
<p>#comment.Comment</p>
<img src="#comment.ImageUrl" alt="img" />
}

Populate Result Set in SelectList MVC3

I have following SelectList declaration in CourseRegisterModel:
public class CourseRegisterModel
{
public StudentModel Student { get; set; }
public CourseModel Course { get; set; }
public IEnumerable<SelectListItem> CoursesList { get; set; }
public DateTime RegisterDate { get; set; }
}
In CourseController I am retrieving all available courses by calling wcf web service:
public ViewResult Index()
{
ServiceCourseClient client = new ServiceCourseClient();
Course[] courses;
courses = client.GetAllCourses();
List<CourseModel> modelList = new List<CourseModel>();
foreach (var serviceCourse in courses)
{
CourseModel model = new CourseModel();
model.CId = serviceCourse.CId;
model.Code = serviceCourse.Code;
model.Name = serviceCourse.Name;
model.Fee = serviceCourse.Fee;
model.Seats = serviceCourse.Seats;
modelList.Add(model);
}
return View(modelList);//RegisterCourses.chtml
}
I need to populate these courses in a dropdown on view RegisterCourses.chtml. How to put all records in selectlist in above code? Also how would i use that selectlist on view?
For starters, your RegisterCourses.cshtml needs to use:
#model <namespace>.CourseRegisterModel
Then, your controller code would be:
public ViewResult Index()
{
ServiceCourseClient client = new ServiceCourseClient();
Course[] courses;
courses = client.GetAllCourses();
CourseRegisterModel model = new CourseRegisterModel();
//model = other model population here
model.CourseList = courses.Select(sl => new SelectListItem()
{ Text = sl.Name,
Value = sl.CId })
.ToList();
return View(model);
}
And finally, back to your view (RegisterCourses.cshtml) - it should contain:
#Html.DropDownListFor(m => m.Course.CId, Model.CourseList)
Use the Html.DropDownList method: http://msdn.microsoft.com/en-us/library/dd492738(v=vs.108).aspx
Pass in the desired name of the drop down list as first argument, as second argument pass in your CourseList:
#Html.DropDownList("CoursesList", Model.CoursesList)

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

I am trying to build a Dropdownlist, but battling with the Html.DropDownList rendering.
I have a class:
public class AccountTransactionView
{
public IEnumerable<SelectListItem> Accounts { get; set; }
public int SelectedAccountId { get; set; }
}
That is basically my view model for now. The list of Accounts, and a property for returning the selected item.
In my controller, I get the data ready like this:
public ActionResult AccountTransaction(AccountTransactionView model)
{
List<AccountDto> accounts = Services.AccountServices.GetAccounts(false);
AccountTransactionView v = new AccountTransactionView
{
Accounts = (from a in accounts
select new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString(),
Selected = false
}),
};
return View(model);
}
Now the problem:
I am then trying to build the Drop down in my view:
<%=Html.DropDownList("SelectedAccountId", Model.Accounts) %>
I am getting the following error:
The ViewData item that has the key 'SelectedAccountId' is of type 'System.Int32' but must be of type 'IEnumerable'.
Why would it want me to return the whole list of items? I just want the selected value. How should I be doing this?
You have a view model to which your view is strongly typed => use strongly typed helpers:
<%= Html.DropDownListFor(
x => x.SelectedAccountId,
new SelectList(Model.Accounts, "Value", "Text")
) %>
Also notice that I use a SelectList for the second argument.
And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:
public ActionResult AccountTransaction()
{
var accounts = Services.AccountServices.GetAccounts(false);
var viewModel = new AccountTransactionView
{
Accounts = accounts.Select(a => new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString()
})
};
return View(viewModel);
}
Step-1: Your Model class
public class RechargeMobileViewModel
{
public string CustomerFullName { get; set; }
public string TelecomSubscriber { get; set; }
public int TotalAmount { get; set; }
public string MobileNumber { get; set; }
public int Month { get; set; }
public List<SelectListItem> getAllDaysList { get; set; }
// Define the list which you have to show in Drop down List
public List<SelectListItem> getAllWeekDaysList()
{
List<SelectListItem> myList = new List<SelectListItem>();
var data = new[]{
new SelectListItem{ Value="1",Text="Monday"},
new SelectListItem{ Value="2",Text="Tuesday"},
new SelectListItem{ Value="3",Text="Wednesday"},
new SelectListItem{ Value="4",Text="Thrusday"},
new SelectListItem{ Value="5",Text="Friday"},
new SelectListItem{ Value="6",Text="Saturday"},
new SelectListItem{ Value="7",Text="Sunday"},
};
myList = data.ToList();
return myList;
}
}
Step-2: Call this method to fill Drop down in your controller Action
namespace MvcVariousApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
RechargeMobileViewModel objModel = new RechargeMobileViewModel();
objModel.getAllDaysList = objModel.getAllWeekDaysList();
return View(objModel);
}
}
}
Step-3: Fill your Drop-Down List of View as follows
#model MvcVariousApplication.Models.RechargeMobileViewModel
#{
ViewBag.Title = "Contact";
}
#Html.LabelFor(model=> model.CustomerFullName)
#Html.TextBoxFor(model => model.CustomerFullName)
#Html.LabelFor(model => model.MobileNumber)
#Html.TextBoxFor(model => model.MobileNumber)
#Html.LabelFor(model => model.TelecomSubscriber)
#Html.TextBoxFor(model => model.TelecomSubscriber)
#Html.LabelFor(model => model.TotalAmount)
#Html.TextBoxFor(model => model.TotalAmount)
#Html.LabelFor(model => model.Month)
#Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")

Categories