C# MVC List and Create in same view - c#

I have a model like this
public class Roles
{
[Key]
public string RoleId {get;set;}
public string RoleName {get;set;}
}
The challenge I have with this is creating a single view for the List and create. Each attempt I have made ended up in data type error. What do I do?

Answer 1:
In Order to hide some fields(as asked in Comments section) in #Html.EditorForModel() you have to use :
[ScaffoldColumn(false)] attribute
Ex :-
[Key]
[ScaffoldColumn(false)]
public string RoleId {get;set;}
Answer 2:
and creating and showing list on the same view :
Model :
public class Roles
{
[Key]
public string RoleId {get;set;}
public string RoleName {get;set;}
public List<Roles> Roleslist { get;set; } //Take a list in Model as shown
}
View :
<div id="mainwrapper">
#using (Html.BeginForm("// Action Name //", "// Controller Name //", FormMethod.Post, new { #id = "form1" }))
{
#Html.TextBoxFor(m => m.RoleName)
<input type="submit" value="Save"/>
}
<div id="RolesList">
#if(Model!=null)
{
if(Model.Roleslist!=null)
{
foreach(var item in Model.Roleslist) //Just Populate Roleslist with values on controller side
{
//here item will have your values of RoleId and RoleName
}
}
}
</div>
</div>

Also check your controller to ensure you are not passing Roles.ToList() to the CreateRole view.
You can do this:
[HttpGet]
public ActionResult CreateRole()
{
var roles = from ur in db.roles
orderby ur.RoleName
select ur;
ViewBag.Listroles = roles.ToList();
return View();
}
where db is your DbContext.
And your view should look like this:
#{
if(ViewBag.Listroles != null){
foreach (var roles in ViewBag.Listroles)
{
<tr>
<td>#roles.RoleName</td>
<td>
#Html.ActionLink("Edit", "EditRoles", new { id=roles.RoleId }) |
#Html.ActionLink("Details", "Details", new { id=roles.RoleId }) |
#Html.ActionLink("Delete", "Delete", new { id=roles.RoleId })
</td>
</tr>
}
}
}
Let me know if my answer helps.

Related

Loop List In View And Bind Values to Model Depending on List Index

I have this Model:
public class ClassRoom
{
public List<Student> Students { get; set; }
}
public class Student
{
public int ID { get; set; }
public int Type { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
}
The values of the ID and Type are already full, I need to create a view where the student can add his name and last name.
So I need to loop the list of students in the view.
I am doing the following:
#model Models.ClassRoom
#{
ViewBag.Title = "Classroom";
}
#if (Model != null)
{
<form action="Controller/Method">
foreach (var item in Model.Students)
{
#Html.HiddenFor(model => model.ID)
<div>
#Html.TextBoxFor(model => model.Name)
#Html.TextBoxFor(model => model.LastName)
</div>
}
<input type="submit">
</form>
}
I want to eventually submit a model of type Classroom with a list of students filled with Name and Last Name for each ID
But this is not working.
How can I bind values From the View to item on a certain index in a list?
For each ID in the hidden input,I want to save the written name and last name.
Please help
I need to create a form and submit the ClassRoom with a full List of Students eventually. What should be the types in my Controller method and views?
If you want to send your model back to controller, then you would need to generate naming correctly. There are several ways, one of them would look like this:
#using (Html.BeginForm("Index", "Home")) {
<div style="margin-top: 100px;">
#if (Model != null) {
for (var i = 0; i <= Model.Students.Count - 1; i++) {
#Html.HiddenFor(model => model.Students[i].ID)
<div>
#Html.TextBoxFor(model => model.Students[i].Name)
#Html.TextBoxFor(model => model.Students[i].LastName)
</div>
}
}
<input type="submit" value="Go"/>
</div>
}
And in controller dont forget to add:
[HttpGet]
public async Task<IActionResult> Index() {
var classroom = new ClassRoom();
... //add some students to the classroom
return View(classroom);
}
[HttpPost]
public async Task<IActionResult> Index(ClassRoom classRoom) {
...
}
Here can be found some more reading.

#Html.RadioButtonFor in mvc

In my application, my model contains a field id, and in the view I need to select an id with a radio button and post back the selected id to the controller. How can I do this? My view is as follows,
#model IList<User>
#using (Html.BeginForm("SelectUser", "Users"))
{
<ul>
#for(int i=0;i<Model.Count(); ++i)
{
<li>
<div>
#Html.RadioButtonFor(model => Model[i].id, "true", new { #id = "id" })
<label for="radio1">#Model[i].Name<span><span></span></span></label>
</div>
</li>
}
</ul>
<input type="submit" value="OK">
}
You need to change you model to represent what you want to edit. It needs to include a property for the selected User.Id and a collection of users to select from
public class SelectUserVM
{
public int SelectedUser { get; set; } // assumes User.Id is typeof int
public IEnumerable<User> AllUsers { get; set; }
}
View
#model yourAssembly.SelectUserVM
#using(Html.BeginForm())
{
foreach(var user in Model.AllUsers)
{
#Html.RadioButtonFor(m => m.SelectedUser, user.ID, new { id = user.ID })
<label for="#user.ID">#user.Name</label>
}
<input type="submit" .. />
}
Controller
public ActionResult SelectUser()
{
SelectUserVM model = new SelectUserVM();
model.AllUsers = db.Users; // adjust to suit
return View(model);
}
[HttpPost]
public ActionResult SelectUser(SelectUserVM model)
{
int selectedUser = model.SelectedUser;
}

Binding to a drop down list in MVC and sending back selection

I am having trouble getting the value of the selected item from a drop down list.
Apologies for how much code I've posted, but it is very simple code to read.
When I edit a vehicle my Get Edit method returns the vehicle and the dropdown list has the correct VehicleType selected in the view.
BUT
When my [HttpPost] Edit gets the model back, the the VehicleType is null, the other fields, name, description are correctly updated.
I have a class called Vehicle and one called VehicleType
public class Vehicle
{
public string Name { get; set; }
public string Description { get; set;
public virtual VehicleType VehicleType { get; set; }
}
public class VehicleType
{
public int VehicleTypeID { get; set; }
public string VehicleTypeDescription { get; set; }
}
in my controller I have an get and set edit methods
public ActionResult Edit(int id = 0)
{
Vehicle myVehicle = db.Vehicle.Find(id);
if (myVehicle == null)
{
return HttpNotFound();
}
PopulateVehicleTypeList(myVehicle.VehicleType.VehicleTypeID);
return View(myVehicle);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Vehicle myVehicle)
{
if (ModelState.IsValid)
{
db.Entry(myVehicle).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(myVehicle);
}
And my view
//View
#model Vehicle
<h2>Edit</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Vehicle</legend>
#Html.HiddenFor(model => model.VehicleID)
<div class="editor-label">
#Html.LabelFor(model => model.VehicleType.VehicleTypeDescription)
</div>
<div class="editor-field">
#Html.DropDownList("VehicleTypeID", String.Empty)
#Html.ValidationMessageFor(model => model.VehicleType.VehicleTypeID)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
There's a few things you should do.
Firstly, create a view Model which has Vehicles and VehicleTypes
public class VehicleViewModel
{
public IEnumerable<SelectListItem> VehicleTypes { get; set; }
public Vehicle vehicle { get; set; }
}
Secondly, in your view , change to DropDownListFor:
#Html.DropDownListFor(
x => x.Vehicle.VehicleType,
Model.VehicleTypes,
"-- Select a vehicle type --", null)
Your controller will look something like this:
VehicleViewModel viewModel = new VehicleViewModel
{
Vehicle vehicle = <populate via Linq query>
VehicleTypes = VehicleTypes.Select(x => new SelectListItem
{
Value = x.VehicleTypeID,
Text = VehicleTypeDescription
}).ToList(),
vehicle = vehicle
};
Hope that helps.

MVC 4 - Many-to-Many relation and checkboxes

I'm working with ASP.NET MVC 4 and Entity Framework. In my database, I have a table Subscription which represents a subscription to public transports. This subscription can provide access to several public transport companies (so a subscription could have 1, 2, 3, ... companies) then it is a Many-to-Many relation between these tables (I have an intermediate table between them).
I want to allow the creation of a subscription throught a page which will contain a field Amount of the subscription and the available companies by checkboxes. Every checkbox represents an existing company (a company stored in my database).
Any idea about how to do that? I've read this ASP.NET MVC Multiple Checkboxes but it was not really helpful.
EDIT : Here is my tables diagram.
You start with two view models. The first one which represents a selected company...
public class CompanySelectViewModel
{
public int CompanyId { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
...and the second one for the subscription to create:
public class SubscriptionCreateViewModel
{
public int Amount { get; set; }
public IEnumerable<CompanySelectViewModel> Companies { get; set; }
}
Then in the SubscriptionControllers GET action you load the companies from the database to initialize the view model:
public ActionResult Create()
{
var viewModel = new SubscriptionCreateViewModel
{
Companies = _context.Companies
.Select(c => new CompanySelectViewModel
{
CompanyId = c.CompanyId,
Name = c.Name,
IsSelected = false
})
.ToList()
};
return View(viewModel);
}
Now, you have a strongly typed view for this action:
#model SubscriptionCreateViewModel
#using (Html.BeginForm()) {
#Html.EditorFor(model => model.Amount)
#Html.EditorFor(model => model.Companies)
<input type="submit" value="Create" />
#Html.ActionLink("Cancel", "Index")
}
To get the company checkboxes rendered correctly you introduce an editor template. It must have the name CompanySelectViewModel.cshtml and goes into the folder Views/Subscription/EditorTemplates (create such a folder manually if it doesn't exist). It's a strongly typed partial view:
#model CompanySelectViewModel
#Html.HiddenFor(model => model.CompanyId)
#Html.HiddenFor(model => model.Name)
#Html.LabelFor(model => model.IsSelected, Model.Name)
#Html.EditorFor(model => model.IsSelected)
Name is added as hidden field to preserve the name during a POST.
Obviously you have to style the views a bit more.
Now, your POST action would look like this:
[HttpPost]
public ActionResult Create(SubscriptionCreateViewModel viewModel)
{
if (ModelState.IsValid)
{
var subscription = new Subscription
{
Amount = viewModel.Amount,
Companies = new List<Company>()
};
foreach (var selectedCompany
in viewModel.Companies.Where(c => c.IsSelected))
{
var company = new Company { CompanyId = selectedCompany.CompanyId };
_context.Companies.Attach(company);
subscription.Companies.Add(company);
}
_context.Subscriptions.Add(subscription);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel);
}
Instead of using Attach you can also load the company first with var company = _context.Companies.Find(selectedCompany.CompanyId);. But with Attach you don't need a roundtrip to the database to load the companies to be added to the collection.
(Edit 2: In this answer is a continuation for the Edit actions and views with the same example model.)
Edit
Your model is not really a many-to-many relationship. You have two one-to-many relationships instead. The PublicTransportSubscriptionByCompany entity is not needed - normally. If you have a composite primary key in that table made of Id_PublicTransportSubscription, Id_PublicTransportCompany and remove the id column Id_PublicTransportSubscriptionByCompanyId EF would detect this table schema as a many-to-many relationship and create one collection in each of the entities for subscription and company and it would create no entity for the link table. My code above would apply then.
If you don't want to change the schema for some reason you must change the POST action like so:
[HttpPost]
public ActionResult Create(SubscriptionCreateViewModel viewModel)
{
if (ModelState.IsValid)
{
var subscription = new Subscription
{
Amount = viewModel.Amount,
SubscriptionByCompanies = new List<SubscriptionByCompany>()
};
foreach (var selectedCompany
in viewModel.Companies.Where(c => c.IsSelected))
{
var company = new Company { CompanyId = selectedCompany.CompanyId };
_context.Companies.Attach(company);
var subscriptionByCompany = new SubscriptionByCompany
{
Company = company
};
subscription.SubscriptionByCompanies.Add(subscriptionByCompany);
}
_context.Subscriptions.Add(subscription);
_context.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel);
}
I prefer this answer: Saving Many to Many relationship data on MVC Create view
If you are doing database first, then just skip to the viewmodel part of section 1.
Just an extension to Slauma's answer. In my case i had to represent many-to-many like a table between Products and Roles, first column representing Products, the header representing Roles and the table to be filled with checkboxes to select roles for product.
To achieve this i have used ViewModel like Slauma described, but added another model containing the last two, like so:
public class UserViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<ProductViewModel> Products { get; set; }
}
public class ProductViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<RoleViewModel> Roles { get; set; }
}
public class RoleViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
Next, in Controller we need to fill data:
UserViewModel user = new UserViewModel();
user.Name = "Me";
user.Products = new List<ProductViewModel>
{
new ProductViewModel
{
Id = 1,
Name = "Prod1",
Roles = new List<RoleViewModel>
{
new RoleViewModel
{
Id = 1,
Name = "Role1",
IsSelected = false
}
// add more roles
}
}
// add more products with the same roles as Prod1 has
};
Next, in View:
#model UserViewModel#using (Ajax.BeginForm("Create", "User",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "divContainer"
}))
{
<table>
<thead>
<tr>
<th>
</th>
#foreach (RoleViewModel role in Model.Products.First().Roles.ToList())
{
<th>
#role.Name
</th>
}
</tr>
</thead>
<tbody>
#Html.EditorFor(model => model.Products)
</tbody>
</table>
<input type="submit" name="Create" value="Create"/>
}
As you see, EditorFor is using template for Products:
#model Insurance.Admin.Models.ProductViewModel
#Html.HiddenFor(model => model.Id)
<tr>
<th class="col-md-2 row-header">
#Model.Name
</th>
#Html.EditorFor(model => model.Roles)
</tr>
This template uses another template for Roles:
#model Insurance.Admin.Models.RoleViewModel
#Html.HiddenFor(model => model.Id)
<td>
#Html.EditorFor(model => model.IsSelected)
</td>
And voila, we have a table containing first column Products, the header contains Roles and the table is filled with checkboxes. We are posting UserViewModel and you will see that all the data are posted.

.net mvc4 HttpPost null value

I have a problem while passing an object with HttpPost...
Once the form is submitted, the model is set "null" on the controller side, and I don't know where is the issue..
Here is my controller :
public ActionResult AddUser(int id = 0)
{
Group group = db.Groups.Find(id);
List<User> finalList = db.Users.ToList() ;
return View(new AddUserTemplate()
{
group = group,
users = finalList
});
//Everything is fine here, the object is greatly submitted to the view
}
[HttpPost]
public ActionResult AddUser(AddUserTemplate addusertemplate)
{
//Everytime we get in, "addusertemplate" is NULL
if (ModelState.IsValid)
{
//the model is null
}
return View(addusertemplate);
}
Here is AddUserTemplate.cs :
public class AddUserTemplate
{
public Group group { get; set; }
public User selectedUser { get; set; }
public ICollection<User> users { get; set; }
}
Here is the form which return a null value to the controller (note that the dropdown list is greatly populated with the good values) :
#using (Html.BeginForm()) {
<fieldset>
<legend>Add an user</legend>
#Html.HiddenFor(model => model.group)
#Html.HiddenFor(model => model.users)
<div class="editor-field">
//Here, we select an user from Model.users list
#Html.DropDownListFor(model => model.selectedUser, new SelectList(Model.users))
</div>
<p>
<input type="submit" value="Add" />
</p>
</fieldset>
}
Thanks a lot for your help
I tried your code and in my case the addusertemplate model was not null, but its properties were all null.
That's because of a few model binding issues: Html.HiddenFor and Html.DropDownListFor do not work with complex types (such as Group or User) (at least that's how it is by default).
Also, Html.HiddenFor cannot handle collections.
Here's how to solve these issues:
instead of #Html.HiddenFor(model => model.group) there should be one #Html.HiddenFor for each property of the group that you need bound
instead of #Html.HiddenFor(model => model.users) you need to iterate through the list of users and for each object add #Html.HiddenFor for each property of the user that you need bound
instead of #Html.DropDownListFor(model => model.selectedUser [...], create a property like int SelectedUserId {get;set;} and use that in the DropDownList (as it cannot handle complex types).
Here's the code that works:
1. The User and Group classes, as I imagined them to be:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Group
{
public int Id { get; set; }
public string Name { get; set; }
}
2. The adjusted AddUserTemplate class:
public class AddUserTemplate
{
public Group Group { get; set; }
public IList<User> Users { get; set; }
public int SelectedUserId { get; set; }
public User SelectedUser
{
get { return Users.Single(u => u.Id == SelectedUserId); }
}
}
The adjustments:
Users was changed from ICollection to IList, because we'll need to access elements by their indexes (see the view code)
added SelectedUserId property, that will be used in the DropDownList
the SelectedUser is not a readonly property, that returns the currently selected User.
3. The adjusted code for the view:
#using (Html.BeginForm())
{
<fieldset>
<legend>Add an user</legend>
#*Hidden elements for the group object*#
#Html.HiddenFor(model => model.Group.Id)
#Html.HiddenFor(model => model.Group.Name)
#*Hidden elements for each user object in the users IList*#
#for (var i = 0; i < Model.Users.Count; i++)
{
#Html.HiddenFor(m => m.Users[i].Id)
#Html.HiddenFor(m => m.Users[i].Name)
}
<div class="editor-field">
#*Here, we select an user from Model.users list*#
#Html.DropDownListFor(model => model.SelectedUserId, new SelectList(Model.Users, "Id", "Name"))
</div>
<p>
<input type="submit" value="Add" />
</p>
</fieldset>
}
Another option that does not require a bunch of hidden fields is to simply specify that you want the model passed to the controller. I think this is much cleaner.
#using(Html. BeginForm("action","controller", Model, FormMethod.Post)){
...
}

Categories