checkboxes matrix with MVC4 - c#

I need to disply a matrix of checkboxes like the one in here
asp.net mvc checkbox/radiobutton matrix model-binding
well, instead of subquestions I haves roles and types, so here is my code:
my models:
public class role
{
public role()
{
types = new List<role_type>();
}
[Key]
public int role_id { get; set; }
public string role_name { get; set; }
public int role_value { get; set; }
public Boolean IsSelected { get; set; }
public IList<role_type> types { get; set; }
}
public class role_type
{
public int Id { get; set; }
public Boolean IsSelected { get; set; }
public string type { get; set; }
}
My view Model:
public class roleViewModel
{
public roleViewModel()
{
Roles = new List<role>();
}
public int ID { get; set; }
public IList<role> Roles { get; set; }
}
My controller:
public class roleviewmodelController : Controller
{
private Context db = new Context();
[HttpGet]
public ActionResult Index(roleViewModel rvm)
{
return View(rvm);
}
}
and my view
#model UsersManagement.Models.roleViewModel
#{
ViewBag.Title = "Index";
}
#for (var i = 0; i < Model.Roles.Count(); i++)
{
<div id="roles">
<ul>
#for (var j = 0; j <4; j++)
{
<li>#Html.CheckBoxFor(m=>Model.Roles[i].types[j].IsSelected)</li>
}
</ul>
</div>
}
this doesn't display anything, what am i missing?
the types should be like (Edit, Delete, Read, Create) and the roles like: manage companies, manage invoices, etc...
PS: My final goal is to customise the authorization system but this is another issue.

Related

Passing wrong model item to view

I'm trying to use two tables in the same View in my asp.net mvc project but I'am doing some errors and I get this error:
System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Data.Entity.Infrastructure.DbQuery1[Question], but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[projet.Models.userdbcontext]
Class Questions.cs:
public class Question
{
public int Id { get; set; }
public int userID { get; set; }
}
Class User.cs:
public class User
{
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Name { get; set; }
}
Model userdbcontext.cs:
{
public userdbcontext()
{ }
public DbSet<Question> Questiondb { get; set; }
public DbSet<User> Usersdb { get; set; }
}
and this is the controller:
private userdbcontext db = new userdbcontext();
// GET: question
public ActionResult Index()
{
var l = from e in db.Questiondb
select e;
return View(l);
}
The view:
#model IEnumerable<projet.Models.userdbcontext>
your error is that you are trying to send a DbSet<> to the view which is hard to manipulate so to solve the problem, you have to create a new class ViewModel in which you store the value of the DbSet<> as List<> then you pass it to the View like this :
Model userdbcontext.cs:
public class userdbcontext : DbContext
{
public userdbcontext()
{ }
public DbSet<Question> Questiondb { get; set; }
public DbSet<User> Usersdb { get; set; }
}
public class ViewModel
{
public List<Question> Question { get; set; }
public List<User> User { get; set; }
}
In the controller:
private userdbcontext db = new userdbcontext();
// GET: question
public ActionResult Index()
{
var l = new ViewModel();
l.Question = db.Questiondb.ToList();
l.User = db.Usersdb.ToList();
return View(l);
}
and in the view:
#model projet.Models.ViewModel
You have to create a view model:
public class ViewModel
{
public List<Question> Questions { get; set; }
public List<User> Users { get; set; }
}
action
public ActionResult Index()
{
var vm = new ViewModel{
Questions = db.Questiondb.ToList(),
Users= db.Userdb.ToList()
}
return View(vm);
}
view
#model projet.Models.ViewModel
....
<!-- Accessing Model Variables -->
#Model.Questions...
#Model.Users...

List item inside model contains null on post

I have a model class. Inside that, I have a class and a list which is that type.
public class ItemSetupModel
{
public class UPC
{
public int ItemNumberForUPC { get; set; }
public string GCOwner { get; set; }
public string GCFeeItem { get; set; }
public string GCBranded { get; set; }
public string query { get; set; }
}
public List<UPC> lstUPC { get; set; }
public UPC upc;
public ItemSetupModel()
{
this.upc = new UPC();
this.lstUPC = new List<UPC>();
this.lstUPC.Add(this.upc);
}
}
cshtml is as below :
#model PricingUpdates.Models.ItemSetupModel
#using (Html.BeginForm())
{
#for (int i = 0; i < Model.lstUPC.Count; i++)
{
#Html.Label("ItemNumberForUPC", "ItemNumber")
#Html.TextBoxFor(m => m.lstUPC[i].ItemNumberForUPC, new { #class = "form-control", Name = "UPCUpdate" + i })
}
}
Whenever I am posting the values, the action result model will never contain the values entered by me in the textbox. It will always show null values for the list.

MVC get child count in Index view

I used scaffolding to create the Index, Details, Create, Edit and Delete views and the controller. I have two view models (Parent / Child) relation. In my Index view I want to display the list of Teams as well as some information on the players (Parent / child). For example I want to display in the Index view the teams with the players count per team and last players that was modified. I am not sure where to begin.
Example:
(Team) Red -- (Last Modified) 01/02/2015 -- (Number Players) 10 and so on.
Team ViewModel
public class TeamVM
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime? LastActivity { get; set; }
public string NumberPlayers { get; set; }
public IList<PLayerVM> PlayerVM { get; set; }
}
Player ViewModel
public class PlayerVM
{
public int ID { get; set; }
public int TeamID { get; set; }
public string PlayerInfo { get; set; }
public DateTime? CreateDate { get; set; }
}
Other ViewModel
public class TeamViewModel
{
public List<Team> Teams{ get; set; }
}
Controller
public ActionResult Index()
{
TeamViewModelviewModel = new TeamViewModel();
viewModel.Teams= db.Teams.ToList();
return View(viewModel);
}
db.Products.ToList()?? I assume that is where you mean db.Teams.ToList()?
You are using viewmodels, so you should map the db data to your viewmodels first:
public ActionResult Index()
{
var teams = db
.Teams
.Include("Players") // Assuming your Team entity has a collection of Players
.SelectMany(t => new TeamVM {
ID = t.ID,
// etc..
})
.ToList();
return View(new TeamViewModel { Teams = teams });
}
model:
public class TeamVM
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime? LastActivity { get; set; }
public IList<PLayerVM> PlayerVM { get; set; }
public int NumberPlayers {
get { return PlayerVM.Count(); }
}
}
Then in your view:
#model MyProject.Models.TeamViewModel
<table>
#foreach(var team in Model.Teams.ToList()) {
<tr>
<td>#team.Name</td> // Name
<td>#team.NumberPlayers</td> // Playercount
<td>#team.PlayerVM.Max(p => p.LastActivity).LastActivity</td> // Last edited
</tr>
}
</table>

MVC : Creating Database using Model class

I am following this MVC tutorial and trying to create a database using DbContext and related model classes. The project name is "odeToFood".
Model classes:
namespace odeToFood.Models
{
public class Restaurant
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public string Country { get; set; }
public ICollection<RestaurantReview> Reviews { get; set; }
}
public class RestaurantReview
{
public int Id { get; set; }
public string Body { get; set; }
public int Rating { get; set; }
public int RestaurantId { get; set; }
}
public class odeToFoodDb :DbContext
{
public DbSet<Restaurant> Restaurants { get; set; }
public DbSet<RestaurantReview> Reviews { get; set; }
}
}
HomeController:
public class HomeController : Controller
{
odeToFoodDb _db = new odeToFoodDb();
public ActionResult Index()
{
var model= _db.Restaurants.ToList();
return View(model);
}
}
Index View
#model IEnumerable<odeToFood.Models.Restaurant>
#{
ViewBag.Title = "Home Page";
}
#foreach (var item in Model)
{
<div>
<h4>#item.Name;</h4>
Restaurant is in : #item.City #item.Country
<hr />
</div>
}
When I run this code, according to this tutorial it should create a database and the values should be fetched (when I enter in table) but in server explorer I cannot find a database.
Neither the Index View gives an error nor can I find a database in server explorer. I tried (Localdb)\v11.0 by going to "add connection" but still it does not show any database.
I would be grateful to know what's wrong.

ViewModel adding custom class to another class

I created this viewmodel:
public class PlayerViewModel
{
PlayerRepository repo = new PlayerRepository();
public Player Player { get; set; }
public int SelectedUserID { get; set; }
public SelectList Users { get; set; }
public PlayerViewModel()
{
Player = new Player();
}
public PlayerViewModel(int id)
{
Player = repo.Retrieve(id);
Users = new SelectList(repo.GetUsers());
SelectedUserID = 0;
}
}
this I have in view:
#Html.DropDownListFor(x => x.SelectedUserID, Model.Users)
#Html.ValidationMessageFor(x => x.SelectedUserID)
and this in controller:
[Authorize]
public ActionResult Upravit(int id)
{
var playerview = new PlayerViewModel(id);
return View(playerview);
}
[Authorize,HttpPost]
public ActionResult Upravit(int id, PlayerViewModel playerView)
{
if (ModelState.IsValid)
{
playerView.Player.User = usRepo.GetUserById(playerView.SelectedUserID);
repo.Save(playerView.Player);
return RedirectToAction("Podrobnosti", new { id = playerView.Player.PlayerID });
}
return View(playerView);
}
Now I have problem that " The field SelectedUserID must be a number." and I have in dropdownlist UserName. I modified this many times, I tried with Dictionary and other ways but everyway has some problem. So I want just ask for best way to add custom class User to class Player.
Player class:
public class Player
{
// pokud použijeme virtual a vlastností tak nám EF rozšíří o další možnosti jako lazy loading a další
[Key]
public int PlayerID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Surname { get; set; }
public string PhotoUrl { get; set; }
public string Post { get; set; }
public virtual Team Team { get; set; }
public virtual User User { get; set; }
// public int UserID { get; set; }
//public virtual ICollection<Article> Articles { get; set; }
// Here could be next things as number, ...
}
Thanks
Use this constructor instead:
http://msdn.microsoft.com/en-us/library/dd505286.aspx
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField
)
Something like this:
Users = new SelectList(repo.GetUsers(),"UserID", "UserName");

Categories

Resources