Dropdown list - MVC3 - c#

I am using C# in ASP MVC3. I have two tables from SQL Server.Table names are SMS_User and SMS_Division in SQL Server 2008. When i create a new user, I want to show division id from sms_division table.
SMS_User contains UserName, DivisionID, EmailAddress
SMS_Division contains DivisionID, DivisionName.
Controller Code :
UserController : Controller
{
private NetPerfMonEntities2 db = new NetPerfMonEntities2();
IEnumerableZamZam= db.SMS_Division.Select(c => new SelectListItem { Value = c.divisionid.ToString(), Text = c.divisionid.ToString() } );
}
When I create a new user in User Create() VIEW I want to show a DivisonName as a dropdown list instead of a text box. How I do that ?
#Html.DropDownListFor(model => model.divisionid, (IEnumerable<SelectListItem>) ViewData["Divisions"], "<--Select a divison-->")
#Html.ValidationMessageFor(model => model.divisionid)
I have this error message :
CS0103: The name 'sms_amountlimit2' does not exist in the current context

I'll be assuming a few missing part of your question in my answer, and give you a generic pattern to have a working dropdown list in ASP.NET MVC 3 :
Let's start with the models :
UserModel would be the class representing the data extracted from sms_user
public class UserModel
{
public string Username { get; set; }
public string EmailAddress { get; set; }
public int DivisionId { get; set; }
}
DivisionModel would be the class representing the data extracted from sms_division
public class DivisionModel
{
public int DivisionId { get; set; }
public string DivisionName { get; set; }
}
By Extracted, I mean anything that can transform the data in your Database in instanciated classes. That can be an ORM (EntityFramework or others), or SQL Queries, etc...
Next, is the viewmodel, because it wouldn't make sense to plug an IEnumerable of divisions in UserModel, and I personally don't really like using ViewData when I can avoid it :
public class UserViewModel
{
public UserModel User { get; set; }
public IEnumerable<DivisionModel> Divisions {get; set;}
}
Next, the controller :
public class UserController : Controller
{
public ActionResult Create()
{
List<DivisionModel> divisions = new List<DivisionModel>();
divisions.Add(new DivisionModel() { DivisionId = 1, DivisionName = "Division1" });
divisions.Add(new DivisionModel() { DivisionId = 2, DivisionName = "Division2" });
UserModel user = new UserModel() { Username = "testUser", EmailAddress = "testAddress#test.com" };
return View(new UserViewModel() { User = user, Divisions = divisions });
}
}
I just create the Division list and the user, but you would get then from you database by any means you are using.
And finally the View :
#model ViewModels.UserViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<p>
#Html.DropDownListFor(model => model.User.DivisionId, new SelectList(Model.Divisions, "DivisionId", "DivisionName"), "-- Select Division --")
#Html.ValidationMessageFor(model => model.User.DivisionId)
</p>
Note that the model binded to the view is the ViewModel.

In your model add a collection of the divisions then create the dropdown list like below:
#Html.DropDownListFor(m => m.SelectedDivisionId,
new SelectList(Model.Divisions, "DivisionId", "DivisionName"),
"-- Select Division --")

Related

MVC 5 MultiSelectList Selected Values Not Working

I have a ListBox in a View displaying the possible choices. However, the user's role(s) are not shown as selected. In my UserViewModel the Roles collection contains the complete list of roles, and AspNetRoles collection contains only the roles to which the user belongs. I've tried multiple examples/variations but nothing ever shows as selected. I'm stuck.
ViewModel:
public class UserViewModel
{
public string Id { get; set; }
public string Email { get; set; }
public ICollection<AspNetRole> Roles { get; set; }
public virtual ICollection<AspNetRole> AspNetRoles { get; set; }
}
Controller:
public ActionResult Edit(string id)
{
UserViewModel user = new UserViewModel();
AspNetUser aspNetUser = new AspNetUser();
if (!string.IsNullOrEmpty(id))
{
aspNetUser = db.AspNetUsers.Find(id);
user.Id = aspNetUser.Id;
user.Email = aspNetUser.Email;
user.AspNetRoles = aspNetUser.AspNetRoles;
var roles = (from r in db.AspNetRoles
select r).ToList();
user.Roles = roles;
}
return View(user);
}
View:
#Html.ListBox("AspNetRoles",
new MultiSelectList(Model.Roles, "Id", "Name",
Model.AspNetRoles.Select(m => m.Id)))
You have not posted your model, but it appears that property AspNetRoles is a collection of a complex object (you cannot bind to a complex object, only a value type - or in the case of ListBox, a collection of value type). You can handle this by changing AspNetRoles to int[] (assuming the ID property of Role is int)
#Html.ListBoxFor(m => m.AspNetRoles, new SelectList(Model.Roles, "Id", "Name"))
Note, Its always better to use the strongly typed helpers.

how to use ICollection for SelectList in Contoller of MVC?

I am developing .NET MVC application.
I want to send the collection of the objects from controller to View using select list.
without using view bag.
ViewModel :
public class AdviceCreateVM
{
public int Id { get; set; }
public string AdviceNo { get; set; }
public ICollection<CompanyVM> Companies { get; set; }
}
public class CompanyVM
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller Code :
public class AdviceCreateController : Controller
{
public ActionResult Create()
{
adviceVM.Companies = new SelectList(ledgerService.GetAll().OrderBy(t => t.Name), "Id", "Name");
}
}
It gives an error -
Cannot implicitly convert type 'System.Web.Mvc.SelectList' to
'System.Collections.Generic.ICollection'. An
explicit conversion exists (are you missing a cast?)
You're trying to assign a SelectList to property of type ICollection<CompanyVM> -- which won't work. You need some like:
var viewModel = new AdviceCreateVM
{
adviceVM.Companies =
ledgerService.GetAll().OrderBy(t => t.Name)
.Select(t=>
new CompanyVM
{
Id = t.Id, // "Id"
Name = t.Name // "Name"
})
.ToList()
};
I'm just guessing on the assignments here, since you didn't specify them.
In the view, you will have to make the select list from Companies property.
#Html.DropDownListFor(model => model.CompanyId,
model.Companies.Select(company =>
new SelectListItem
{
Value = company.Id,
Text = company.Name
}), "--Select Company--")
As indicated in the comments, SelectList does not implement ICollection. Change you view model collection to SelectList
public class AdviceCreateVM
{
public int Id { get; set; }
public string AdviceNo { get; set; }
public SelectList Companies { get; set; } // change to select list
public int CompanyID { get; set; } // for binding the the drop down list
}
Controller
public ActionResult Create()
{
AdviceCreateVM model = new AdviceCreateVM(); // initialise model
model.Companies = new SelectList(ledgerService.GetAll().OrderBy(t => t.Name), "Id", "Name");
}
View
#model YourAssembly.AdviceCreateVM
#using (Html.BeginForm()) {
....
#Html.DropDownFor(m => m.CompanyID, Model.Companies)
...

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

Binding a DropDownList in the view to a column in table using ASP.NET MVC4

I'm brand new to ASP.NET MVC, and I would appreciate any help with my question. I already did plenty of research (not enough apparently) on this topic. I need to bind a dropdownlist to a specific column in a table and then render it in the view. I already have the query to retrieve the table in the controller:
public ActionResult SelectAccountEmail()
{
var queryAccountEmail = (from AccountEmail in db.UserBases select AccountEmail)
var selectItems = new SelectList(queryAccountEmail);
return View(selectItems);
}
I get lost when it come to binding the query to a dropdownlist in the view.
#model RecordUploaderMVC4.Models.UserBase
#{
ViewBag.Title = "SelectAccountEmail";
}
<h2>SelectAccountEmail</h2>
#Html.LabelFor(model => model.AccountEmail);
#Html.DropDownList(Model.AccountEmail);
#Html.ValidationMessageFor(model => model.AccountEmail);
<input /type="submit" value="Submit">
I get this error when I run it:
Server Error in '/' Application.
--------------------------------------------------------------------------------
The model item passed into the dictionary is of type 'System.Web.Mvc.SelectList', but this dictionary requires a model item of type 'RecordUploaderMVC4.Models.UserBase'.
Any help will be appreciated.
Thanks in advance.
Few things wrong. Firstly, change your model to add the following properties (Looking at your view, it's RecordUploaderMVC4.Models.UserBase):
public class UserBase
{
public string AccountEmail { get; set; }
public SelectList Emails { get; set; }
//rest of your model
}
Then, build your model in your controller properly:
public ActionResult SelectAccountEmail()
{
UserBase model = new UserBase();
var queryAccountEmail = (from AccountEmail in db.UserBases select AccountEmail)
model.Emails = new SelectList(queryAccountEmail);
return View(model);
}
Then in your view you can do:
#Html.LabelFor(model => model.AccountEmail)
#Html.DropDownListFor(model => model.AccountEmail, Model.Emails)
#Html.ValidationMessageFor(model => model.AccountEmail)
Step 1:
First Create a model Like this to hold your ListofAccountEmail
public class AccountEmailViewModel
{
public int AccountEmailId { get; set; }
public string AccountEmailDescription { get; set; }
}
Step 2: Create your model class
public class UserBaseViewModel
{
public IEnumerable<SelectListItem> AccountEmail { get; set; }
public string AccountEmail { get; set; }
}
Step 3 :
In Controller
[HttppGet]
public ActionResult SelectAccountEmail()
{
var EmailAccounts = (from AccountEmail in db.UserBases select AccountEmail)
UserBase userbaseViewModel = new UserBase
{
AccountEmail = EmailAccounts.Select(x => new SelectListItem
{
Text = x.AccountEmailDescription,
Value = Convert.ToString(x.AccountEmailId)
}).ToList()
};
return View(userbaseViewModel);
}
Step 4 : In View
#model RecordUploaderMVC4.Models.UserBase
#{
ViewBag.Title = "SelectAccountEmail";
}
<h2>SelectAccountEmail</h2>
#Html.ValidationSummary()
<h2>SelectAccountEmail</h2>
#Html.LabelFor(model => model.AccountEmail )
#Html.DropDownListFor(x => x.AccountEmailId, Model.AccountEmail, "Please Select", "")
</div>
<input /type="submit" value="Submit">

How to print after join linq query

I have this code:
public ActionResult Index()
{
MembershipUser currentUser = Membership.GetUser();
Guid UserId = (Guid)currentUser.ProviderUserKey;
var users = from m in db.Users
join m2 in db.MyProfiles on m.UserId equals m2.UserId
where m.UserId == UserId
select new{UserName = m.UserName, LastActivityDate = m.LastActivityDate,
Address = m2.Address, City = m2.City, State = m2.State, Zip = m2.Zip};
return View(users);
}
This code is in my Controller, I want to run this query and then print the results into my view, how would I write the view?
//if your question is how to display(Print!) a view for above query then in ActionResult Index()
//1] As as best practise always Create a ViewModel - UserViewModel
public class UserviewModel
{
public string Username {get;set;}
public string Address {get;set;}
}
//2] Assign db.user values to UserviewModel or you can use Automapper
//and 3] then return this viewmodel to view
return View(UserviewModel);
This code cannot work because your LINQ query is returning an anonymous object so you cannot strongly type your view. So the first step would be to define a view model which will represent the information you are willing to display on your view:
public class UserViewModel
{
public string UserName { get; set; }
public DateTime LastActivityDate { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
then in your controller action you would return a collection of this view model:
public ActionResult Index()
{
var currentUser = Membership.GetUser();
var userId = (Guid)currentUser.ProviderUserKey;
var users =
from m in db.Users
join m2 in db.MyProfiles on m.UserId equals m2.UserId
where m.UserId == userId
select new UserViewModel
{
UserName = m.UserName,
LastActivityDate = m.LastActivityDate,
Address = m2.Address,
City = m2.City,
State = m2.State,
Zip = m2.Zip
};
return View(users);
}
and finally in your strongly typed view:
#model IEnumerable<AppName.Models.UserViewModel>
#Html.DisplayForModel()
and in the corresponding display template (~/Views/Shared/DisplayTemplates/UserViewModel.cshtml) which will be rendered for each item of the collection:
#model AppName.Models.UserViewModel
<div>
Username: #Html.DisplayFor(x => x.UserName)<br/>
Last activity: #Html.DisplayFor(x => x.LastActivityDate)<br/>
...
</div>
You need to get the type of users and make a List-View of that type. Easiest way to make a view is simply right-clicking in your controller method and selecting Create View. That'll make sure the routing gets done properly as well.

Categories