Problems with MVC 3 dropdownlist in webgrid - asp.net-mvc-3

I'm trying to display a dropdown list in a webgrid, but I can't get it to work :(
I'm getting the following error: (on last column in the view)
The best overloaded method match for
'System.Web.Helpers.WebGrid.Column(string, string,
System.Func, string, bool)' has some invalid
arguments \Visual Studio
2010\Projects\foo\bar\Views\Admin\ManageRoles.cshtml
Hope you can make sense of the code.
Model:
public class UserViewModel
{
[Display(Name = "User name")]
public string Name { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
public string Role { get; set; }
public IEnumerable<SelectListItem> Roles1 { get; set; }
public string Email { get; set; }
}
Controller
public ActionResult ManageRoles()
{
var users = Membership.GetAllUsers().Cast<MembershipUser>().Select(x => new UserViewModel
{
Name = x.UserName,
Email = x.Email,
Roles1 = RolesList,
Role = Roles.GetRolesForUser(x.UserName).FirstOrDefault()
});
ViewBag.Roles = users;
return View(users);
}
public IEnumerable<SelectListItem> RolesList
{
get
{
return Roles.GetAllRoles()
.Select(x => new SelectListItem
{
Value = x,
Text = x
})
.ToList();
}
}
View:
#model IEnumerable<UserViewModel>
#{
ViewBag.Title = "ManageRoles";
var grid = new WebGrid(source: Model, defaultSort: "Name");
}
<h2>ManageRoles</h2>
#grid.GetHtml(
columns: grid.Columns(
grid.Column("Name"),
grid.Column("Email"),
grid.Column("ListItemId", "Role", format: ((item) => Html.DropDownListFor(item.Role, item.Roles1)))
)
)

Related

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Dept_IDs'

The dropdown works fine. It fetches the values from the database but when i insert the selected value into a table. It gives me the error, tried a lot of different ways but didn't work.
View:
#Html.DropDownList(model => model.Dept_ID, ViewBag.deptlistname as
SelectList, "Please select a department");
Controllers:
public ActionResult UserRegistration()
{
HREntities4 db = new HREntities4();
var getdeptlist = db.departments.ToList();
SelectList list = new SelectList(getdeptlist, "Dept_ID",
"Dept_ID");
ViewBag.deptlistname = list;
return View();
}
Post:
[HttpPost]
public ActionResult UserRegistration(UserRegistration model)
{
if (ModelState.IsValid)
{
var details = new HREntities4();
details.logins.Add(new login{
FirstName = model.FirstName,
LastName = model.LastName,
Username = model.Username,
Email = model.Email,
Password = model.Password,
PhoneNumber =model.PhoneNumber,
Address = model.Address,
Hire_Date = model.Hire_Date,
Salary = model.Salary,
Dept_ID = model.Dept_ID
});
details.SaveChanges();
ModelState.AddModelError("updated", "User has been registered");
}
return View();
}
ViewModel:
public partial class UserRegistration
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }
public string Hire_Date { get; set; }
public Nullable<double> Salary { get; set; }
public int Dept_ID { get; set; }
}
Remove the 's' from Dept_IDs because in your UserRegistration model you have Dept_ID.

validation failing on dropdown MVC

I am using code-first with EF. Validation seems to be failing on a dropdown list with the error System.NullReferenceException: Object reference not set to an instance of an object. This happens when I save a record and I intentionally leave controls empty to test the validation. It happens even if the dropdown list itself has a selection.
here is part of my view:
<div class="editor">
#Html.LabelFor(model => model.EmployeeID)
#Html.DropDownListFor(model => model.EmployeeID, new SelectList(Model.Employees, "Value", "Text"))
#Html.ValidationMessageFor(model => model.EmployeeID)
</div>
If I use a textbox validation works:
<div class="editor">
#Html.LabelFor(model => model.EmployeeID)
#Html.TextBoxFor(model => model.EmployeeID, new { style = "width: 250px;" })
#Html.ValidationMessageFor(model => model.EmployeeID)
</div>
here are my Create controller actions:
public ActionResult Create()
{
var e = iEmployeeRepository.GetAll();
var visitorLogViewModel = new VisitorLogViewModel
{
Employees = e.Select(x => new SelectListItem
{
Value = x.EmployeeID,
Text = x.EmployeeName
})
};
return View(visitorLogViewModel);
}
//
// POST: /VisitorLogs/Create
[HttpPost]
public ActionResult Create(VisitorLog visitorlog)
{
if (ModelState.IsValid) {
iVisitorlogRepository.Add(visitorlog);
iVisitorlogRepository.Save();
return RedirectToAction("Search");
} else {
return View();
}
}
And my viewmodel:
public class VisitorLogViewModel
{
public int Id { get; set; }
[Display(Name = "Visitor Name")]
public string VisitorName { get; set; }
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
[Required(ErrorMessage = "Employee ID is required.")]
[Display(Name = "GB Employee")]
public string EmployeeID { get; set; }
[Display(Name = "Visit Reason")]
public string VisitReason { get; set; }
[Display(Name = "Time In")]
public DateTime TimeIn { get; set; }
[Display(Name = "Time Out")]
public DateTime TimeOut { get; set; }
[Display(Name = "GB Employee")]
public string EmployeeName { get; set; }
public IEnumerable Employees { get; set; }
public VisitorLog VisitorLog { get; set; }
}
And my partial model for validation:
[MetadataType(typeof(VisitorLogMetaData))]
public partial class VisitorLog
{
}
public class VisitorLogMetaData
{
[Required(ErrorMessage = "Visitor name is required.")]
[MaxLength(128)]
public string VisitorName { get; set; }
[Required(ErrorMessage = "Company name is required.")]
[MaxLength(128)]
public string CompanyName { get; set; }
[Required(ErrorMessage = "GB Employee is required.")]
[MaxLength(128)]
public string EmployeeID { get; set; }
[Required(ErrorMessage = "Visit reason is required.")]
[MaxLength(254)]
public string VisitReason { get; set; }
[Required(ErrorMessage = "Time in is required.")]
public DateTime TimeIn { get; set; }
[Required(ErrorMessage = "Time out reason is required.")]
public DateTime TimeOut { get; set; }
}
And finally my model:
public partial class VisitorLog
{
public int Id { get; set; }
public string VisitorName { get; set; }
public DateTime TimeIn { get; set; }
public DateTime TimeOut { get; set; }
public string CompanyName { get; set; }
public string EmployeeID { get; set; }
public string VisitReason { get; set; }
// Navigation properties
[ForeignKey("EmployeeID")]
public virtual Employee Employee { get; set; }
}
I read there was a bug in MVC razor regarding the DropDownListFor but I don't know if that applies in my situation. I have tried some of the solutions and they didn't work for me. I am using 4.5 framework.
Thanks.
Edit:
One thing I noticed, when I submit the page and the error stops on the dropdown element:
#Html.DropDownListFor(model => model.EmployeeID, new SelectList(Model.Employees, "Value", "Text"))
the Model in Model.Employees is null, like it is loosing its binding when the page is submited.
Ok, I did some fundemental changes to my classes. First, I changed the post method in my controller. Previously I was passing the model to the post, now I am passing the view model and mapping it to the model before saving via my repository:
//
// POST: /VisitorLogs/Create
[HttpPost]
public ActionResult Create(VisitorLogViewModel visitorLogViewModel)
{
var e = iEmployeeRepository.GetAll();
VisitorLog visitorLog = new VisitorLog();
visitorLog.Id = visitorLogViewModel.Id;
visitorLog.VisitorName = visitorLogViewModel.VisitorName;
visitorLog.CompanyName = visitorLogViewModel.CompanyName;
visitorLog.EmployeeID = visitorLogViewModel.EmployeeID;
visitorLog.TimeIn = visitorLogViewModel.TimeIn;
visitorLog.TimeOut = visitorLogViewModel.TimeOut;
visitorLog.VisitReason = visitorLogViewModel.VisitReason;
visitorLogViewModel.Employees = new SelectList(e, "EmployeeID", "EmployeeName");
if (ModelState.IsValid)
{
iVisitorlogRepository.Add(visitorLog);
iVisitorlogRepository.Save();
return RedirectToAction("Search");
} else {
return View(visitorLogViewModel);
}
}
Next, I had to add the "required" attribute (validation) to the viewmodel:
public class VisitorLogViewModel
{
public int Id { get; set; }
[Required(ErrorMessage = "Visitor name is required.")]
[MaxLength(128)]
[Display(Name = "Visitor Name")]
public string VisitorName { get; set; }
[Required(ErrorMessage = "Company name is required.")]
[MaxLength(128)]
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
[Required(ErrorMessage = "GB Employee is required.")]
[MaxLength(16)]
[Display(Name = "GB Employee")]
public string EmployeeID { get; set; }
[Required(ErrorMessage = "Visit Reason is required.")]
[MaxLength(254)]
[Display(Name = "Visit Reason")]
public string VisitReason { get; set; }
[Display(Name = "Time In")]
public DateTime TimeIn { get; set; }
[Display(Name = "Time Out")]
public DateTime TimeOut { get; set; }
[Display(Name = "GB Employee")]
public string EmployeeName { get; set; }
public SelectList Employees { get; set; }
}
Not sure if that is the most effcient method but everything works now. If someone sees something wrong with this method let me know.

WebGrid MVC 3 with RadioButton Get Selected

how I can make the WebGrid as appears in the picture and get the selected row with the rariobutton
Blessings
Try this
myGrid.Column(header: "Select", format: #<text><input name="chck"
TYPE="RADIO" CHECKED="#item.select" /></text>),
Also check this link http://fiddle.jshell.net/Gt4GH/
This is not a compiled code, try this and let me know if it works :)
You could define view models:
public class UserViewModel
{
public int Id { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class MyViewModel
{
public int? SelectedUserId { get; set; }
public IEnumerable<UserViewModel> Users { get; set; }
}
then a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var users = Enumerable.Range(1, 5).Select(x => new UserViewModel
{
Id = x,
Email = "email " + x,
FirstName = "fn " + x,
LastName = "ln " + x,
});
var model = new MyViewModel
{
Users = users
};
return View(model);
}
[HttpPost]
public ActionResult Index(int? selectedUserId)
{
return Content(string.Format("Thank you for selecting user id: {0}", selectedUserId));
}
}
and finally a view:
#model MyViewModel
#{
var grid = new WebGrid(Model.Users);
}
#using (Html.BeginForm())
{
#grid.GetHtml(
columns: grid.Columns(
grid.Column(
header: "Select",
format: #<text>#Html.RadioButtonFor(x => x.SelectedUserId, (int)item.Id)</text>
),
grid.Column("Email"),
grid.Column("FirstName", "First Name"),
grid.Column("LastName", "Last Name")
)
)
<button type="submit">OK</button>
}

How to make dropdownlist

How make a dropdownlist? [Edited - almost working code]
View:
<div class="editor-label">
Firma
<div class="editor-field">
#Html.DropDownListFor(x => x.ID_firma, Model.firmaList)
#Html.ValidationMessageFor(model => model.nazwa)
</div>
Model:
public class produktModel
{
[Required(ErrorMessage="Proszę podać nazwę.")]
public string nazwa { get; set; }
[Required(ErrorMessage = "Proszę podać ilść produktu.")]
public decimal ilosc { get; set; }
[Required(ErrorMessage = "Proszę podać jednostkę produktu (np. kg, l, szt.).")]
public string jednostka { get; set; }
[Required(ErrorMessage = "Proszę podać cenę produktu.")]
public decimal cena { get; set; }
public string ID_firma { get; set; }
public IEnumerable<SelectListItem> firmaList { get; set; }
}
Controller:
public ActionResult dodaj()
{
var firma = baza.Firmas;
var model = new produktModel
{
firmaList = firma.AsEnumerable().Select(x => new SelectListItem
{
Value = x.ID_firma.ToString(),
Text = x.nazwa
})
};
return View(model);
}
[HttpPost]
public ActionResult dodaj(produktModel model)
{
Produkt prod = new Produkt();
prod.nazwa = model.nazwa;
prod.ilosc = model.ilosc;
prod.jednostka = model.jednostka;
prod.cena = model.cena;
prod.ID_firma = model.ID_firma;
baza.Produkts.InsertOnSubmit(prod);
baza.SubmitChanges();
return RedirectToAction("zarzadzaj_produktami", "Produkt");
}
It almost work...
I have only one problem (I hope)...
Value is string, and I save his value to database... (I don't now how to write it...)
prod.ID_firma = model.ID_firma;
prod.ID_firma is int. model.ID_firma is this value which is string. So I have an error:
Error 1 Cannot implicitly convert type 'string' to 'int?'
change your model a bit, i have assumed the column names change them according to your code
public class produktModel
{
[Required]
public string name { get; set; }
public decimal price { get; set; }
[Required]
public int companyID {get; set;}
public List<Company> compList {get; set;}
}
public class Company{
public int CompanyID {get;set;}
public string CompanyName {get;set;}
}
ActionResult should look like
public ActionResult add()
{
produktModel model = new produktModel();
model.compList= (from b in base.Companies
select new Company{
CompanyID = b.CompanyID,
CompanyName = b.CompanyName
}).ToList();
return View(model);
}
in your (strongly typed) view
#model produktModel
....
<div class="editor-label">
Company
<div class="editor-field">
#Html.DropDownListFor(model => model.companyID,
new SelectListItem(model.compList,
"CompanyID ",
"CompanyName "))
#Html.ValidationMessageFor(model => model.company_name)
</div>
...
Your question isn't clear enough.
Any way you can use the telerik combox\dropdown list or the default mvc dropdown list. you can find a lot of examples on google for that.
With Telerik write something like this:
#(Html.Telerik().ComboBox()
.Name("ComboBox")
.BindTo(new SelectList("CompanyID", "CompanyName")))
see this Telerik demo for more information.

Bind dropdown list from database

I have been struggling to create a Dropdown list which will display Country names from database.
The situation is:
I have a Controller "AdvertisementController", a model"AdvertisementModel" and a View "Create.cshtml".
On the view I need to create a dropdown list which will display country names from database.
I know the good thing will be to create a Viewmodel. But how shall I do that?
A bunch of code will be much appreciated. :)
I have the following code but it shows 'null reference' error.
Viewmodel:
public class CommunicationViewModel
{
public string CategoryID { get; set; }
public IEnumerable<SelectListItem> CategoryList { get; set; }
}
Model:
public class CreateAdModel
{
[Required]
[Display(Name = "Title")]
public string Title { get; set; }
[Required]
[Display(Name = "Description")]
[DataType(DataType.MultilineText)]
public string Message { get; set; }
[Required]
[Display(Name = "Ad type")]
public string AdType { get; set; }
[Required]
[Display(Name = "Ad category")]
public string AdCategory { get; set; }
public CommunicationViewModel categories { get; set; }
}
Controller:
public ActionResult Index()
{
var query = db.AddCategory.Select(c => new SelectListItem
{
Value = c.ID.ToString(),
Text = c.Name
}
);
var model = new CommunicationViewModel { CategoryList = query.AsEnumerable() };
return View(model);
}
Razor:
#Html.DropDownListFor(m=>m.categories.CategoryID,Model.categories.CategoryList,"--Select one--")
This may help you. Drop down for roles when adding users. very simple tutorial
http://rtur.net/blog/post/2009/06/03/Quick-and-dirty-role-management-in-ASPNET-MVC.aspx

Resources