MVC 3, Radio buttons & Models - asp.net-mvc-3

Given I have a Model object like ...
public class MyModel
{
public int SomeProperty { get; set; }
public int SomeOtherProperty { get; set; }
public IList<DeliveryDetail> DeliveryDetails { get; set; }
}
public DeliveryDetail
{
public string Description { get; set; }
public bool IsSelected { get; set; }
}
and I pass it through to a View like this ...
// Controller
public ActionResult Index()
{
MyModel myModel = Factory.CreateModelWithDeliveryDetails(x);
return View(myModel);
}
How would I render / bind a set of radio buttons (in the view)? Using the following code doesn't post the data back:
#foreach(var deliveryDetail in #Model.DeliveryDetails)
{
#deliveryDetail.Description
#Html.RadioButtonFor(x => deliveryDetail, false)
}

Selections in a radio button list are mutually exclusive. You can select only a single value. So binding a radio button list to a property of type IEnumerable doesn't make any sense. You probably need to adapt your view model to the requirements of the view (which in your case is displaying a radio button list where only a single selection can be made). Had you used a checkbox list, binding to an IEnumerable property would have made sense as you can check multiple checkboxes.
So let's adapt the view model to this situation:
Model:
public class MyModel
{
public string SelectedDeliveryDetailId { get; set; }
public IList<DeliveryDetail> DeliveryDetails { get; set; }
}
public class DeliveryDetail
{
public string Description { get; set; }
public int Id { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyModel
{
DeliveryDetails = new[]
{
new DeliveryDetail { Description = "detail 1", Id = 1 },
new DeliveryDetail { Description = "detail 2", Id = 2 },
new DeliveryDetail { Description = "detail 3", Id = 3 },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyModel model)
{
// Here you will get the id of the selected delivery detail
// in model.SelectedDeliveryDetailId
...
}
}
View:
#model MyModel
#using (Html.BeginForm())
{
foreach (var deliveryDetail in Model.DeliveryDetails)
{
#deliveryDetail.Description
#Html.RadioButtonFor(x => x.SelectedDeliveryDetailId, deliveryDetail.Id)
}
<button type="submit">OK</button>
}

You need another property for posted value::
public class MyModel
{
public int SomeProperty { get; set; }
public int SomeOtherProperty { get; set; }
public IList<DeliveryDetail> DeliveryDetails { get; set; }
public DeliveryDetail SelectedDetail { get; set; }
}
And in view:
#foreach(var deliveryDetail in #Model.DeliveryDetails)
{
#deliveryDetail.Description
#Html.RadioButtonFor(x => x.SelectedDetail, deliveryDetail)
}
In order this to work DeliveryDetail has to be Enum.

Related

While filtering, how to POST a SearchModel, but GET a different ResultsModel back in the view

I am creating a filter view to find records. This example on SO helps, but does not mention how handle the (Filtered) View.
The err below is because, the actions returns a List<ProductViewModel>, and it Errors/complains that the View is using a SearchViewModel, I need to this POST the searchmodel/variables, butGET back the list/results model
The model item passed into the dictionary is of type
'System.Collections.Generic.List`1[ViewModels.ProductVM]', but this
dictionary requires a model item of type 'ViewModels.SearchModel'.
Issue/Question: Since there are two models, the SearchViewModel passed to the controller & the ProductViewModel returned as a result, which model should be strongly typed to the view? and How can I create the view to handle both SearchModel & ProductModel If I stronglyType ProductVM, then I loose the submitform from the SearchVM.
I create the SearchView as the mainview, & the _ResultsPartialView as a partialView, is this wrong?
public ActionResult Index(SearchModel searchModel)
{
var filteredProdVMList = _Repository.GetFilteredProducts(searchModel);
return View(filteredProdVMList);
}
public class ProductVM
{
public int Id { get; set; }
public int Price { get; set; }
public string Name { get; set; }
// implicit const... blah.. removed
}
public class SearchModel
{
public int? Id { get; set; }
public int? PriceFrom { get; set; }
public int? PriceTo { get; set; }
public string Name { get; set; }
}
You need to modify your SearchModel to include a collection property for the products
public class SearchModel
{
public int? PriceFrom { get; set; }
public int? PriceTo { get; set; }
....
public IEnumerable<ProductVM> Products { get; set; } // add
}
then you return just SearchModel to your view
public ActionResult Filter(SearchModel filter)
{
filter.Products = _repository.GetFilteredProducts(filter);
return View(filter);
}
and your view will be
#model SearchModel
....
#using (Html.BeginForm("Filter", "yourControllerName", FormMethod.Get))
{
#Html.LabelFor(m => m.PriceFrom)
#Html.EditorFor(m => m.PriceFrom)
#Html.ValidationMessageFor(m => m.PriceFrom)
... // other form controls for properties you want to filter the results on
<input type="submit" value="Filter" />
}
#Html.Partial("_ResultsPartialView", Model.Products)

how to bind a dropdownlist to model properly to be able to pass values back from view to controller

I am trying to update a compound page model which as one of its properties has a list of objects.
My Model looks like this:
public class PageViewModel
{
public ProgramListVM ProgramsDDL { get; set; }
public PageViewModel()
{
this.ProgramsDDL = new ProgramListVM();
}
}
The ProgramListVM class is:
public class ProgramListVM
{
public List<ProgramVM> Program_List { get; set; }
public int SelectedValue { get; set; }
public ProgramListVM()
{
this.Program_List = new List<ProgramVM>();
this.SelectedValue = 0;
}
}
and ProgramVM is:
public class ProgramVM
{
public int ProgramID { get; set; }
public string ProgramDesc { get; set; }
public ProgramVM(int id, string code)
{
this.ProgramID = id;
this.ProgramDesc = code;
}
}
I try to render this dropdownlist by the following two:
1-
<%: Html.DropDownList("ProgramsDDL", new SelectList(Model.Page6VM.ProgramsDDL.Program_List, "ProgramID", "ProgramDesc", Model.Page6VM.ProgramsDDL.SelectedValue))%>
2-
<%: Html.DropDownListFor(m => m.Page6VM.ProgramsDDL.Program_List, new SelectList(Model.Page6VM.ProgramsDDL.Program_List, "ProgramID", "ProgramDesc"), Model.Page6VM.ProgramsDDL.SelectedValue)%>
But when I try to update my model through a controller action
[HttpPost]
public ActionResult UpdateUser(PageViewModel model)
{
}
model.ProgramsDDL.count is zero.
What is the best way to render this dropdownlist and be able to set the selected index, and also be able to send the selected index back to the controller?
You mixed up the parameters for Html.DropDownListFor(). Code sample below should work.
<%: Html.DropDownListFor(m => m.SelectedValue,
new SelectList(Model.Page6VM.ProgramsDDL.Program_List, "ProgramID", "ProgramDesc"),
null) %>
You also should have a SelectedValue in your model that's posted back.
public class PageViewModel
{
public ProgramListVM ProgramsDDL { get; set; }
public int SelectedValue { get; set; }
public PageViewModel()
{
this.ProgramsDDL = new ProgramListVM();
}
}
Also default model binder can't map complex collections to your model. You probably don't need them in your post action anyway.

ViewBag multiple SelectList for dropdown list

I am trying to use dropdownList with two foreign keys which are modelId, and categoryId.
And I am using ViewBag with selectList.
public ActionResult Create()
{
ViewBag.categoryId = new SelectList(db.Category, "categoryId", "name");
ViewBag.modelId = new SelectList(db.Model, "modelId", "name");
return View();
}
//
// POST: /Product/Create
[HttpPost]
public ActionResult Create(Product product)
{
if (ModelState.IsValid)
{
db.Product.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.categoryId = new SelectList(db.Category, "categoryId", "name", product.categoryId);
ViewBag.modelId = new SelectList(db.Model, "modelId", "name", product.modelId);
return View(product);
}
And here is my Create.cshtml.
<div class="editor-label">
#Html.LabelFor(model => model.Category)
</div>
<div class="editor-field">
#Html.DropDownList("categoryId", "--Select--")
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Model)
</div>
<div class="editor-field">
#Html.DropDownList("modelId", "--Select--")
</div>
When I press submit button, error come up,
'An item with the same key has already been added'
What is problem? Is it problem with in Model?
Here is my models.
--Prodruct.cs--
public class Product
{
[Key] public int productId { get; set; }
[Required(ErrorMessage = "Please select category")]
public int categoryId { get; set; }
[Required(ErrorMessage = "Please select model")]
public int modelId { get; set; }
[DisplayName("Model name")]
public String model { get; set; }
public virtual Category Category { get; set; }
public virtual Model Model { get; set; }
}
--Category.cs--
public class Category
{
[Key] public int categoryId { get; set; }
public String name { get; set; }
}
--Model.cs--
public class Model
{
[Key] public int modelId { get; set; }
public String name { get; set; }
}
--RentalDB.cs--
public class rentalDB : DbContext
{
public DbSet<Product> Product { get; set; }
public DbSet<Model> Model { get; set; }
public DbSet<Customer> Customer { get; set; }
public DbSet<Order> Order { get; set; }
public DbSet<Cart> Cart { get; set; }
public DbSet<Category> Category { get; set; }
public DbSet<OrderDetails> OrderDetails { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
Where it is wrong? Index page in Create can get category data and model data. However, when I submit it, it has error, 'An item with the same key has already been added'.
Could you help me where has got problem?
Thank you.
--added more coding--
I am using this LINQ. Probably here has problem.
How can I add 'Model' entity in here?
var product = from a in db.Product.Include(a => a.Category)
select a;
This is how I would have done it..
I would suggest that you don't send your domain models to the view, but rather create a view model for each view. Doing it this way you will only include what is needed on the screen.
Create a new view model for your Create view:
public class ProductCreateViewModel
{
// Include other properties if needed, these are just for demo purposes
public string Name { get; set; }
public string SKU { get; set; }
public string LongDescription { get; set; }
// This is the unique identifier of your category,
// i.e. foreign key in your product table
public int CategoryId { get; set; }
// This is a list of all your categories populated from your category table
public IEnumerable<Category> Categories { get; set; }
// This is the unique identifier of your model,
// i.e. foreign key in your product table
public int ModelId { get; set; }
// This is a list of all your models populated from your model table
public IEnumerable<Model> Models { get; set; }
}
Category class:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
Model class:
public class Model
{
public int Id { get; set; }
public string Name { get; set; }
}
In your Create view you would have the following:
#model MyProject.ViewModels.ProductCreateViewModel
#using (Html.BeginForm())
{
<table>
<tr>
<td><b>Category:</b></td>
<td>
#Html.DropDownListFor(x => x.CategoryId,
new SelectList(Model.Categories, "Id", "Name", Model.CategoryId),
"-- Select --"
)
#Html.ValidationMessageFor(x => x.CategoryId)
</td>
</tr>
<tr>
<td><b>Model:</b></td>
<td>
#Html.DropDownListFor(x => x.ModelId,
new SelectList(Model.Models, "Id", "Name", Model.ModelId),
"-- Select --"
)
#Html.ValidationMessageFor(x => x.ModelId)
</td>
</tr>
</table>
<!-- Add other HTML controls if required and your submit button -->
}
Your Create action methods:
public ActionResult Create()
{
ProductCreateViewModel viewModel = new ProductCreateViewModel
{
// Here you do database calls to populate your dropdowns
Categories = categoryService.GetAllCategories(),
Models = modelService.GetAllModels()
};
return View(viewModel);
}
[HttpPost]
public ActionResult Create(ProductCreateViewModel viewModel)
{
// Check that viewModel is not null
if (!ModelState.IsValid)
{
viewModel.Categories = categoryService.GetAllCategories();
viewModel.Models = modelService.GetAllModels();
return View(viewModel);
}
// Mapping
Product product = ... // Do your mapping here
// Insert product in database
productService.Insert(product);
// Return the view where you need to be
}
I would also recommend that you use AutoMapper to do the mappings for you between your domain model and view model. I would also recommend that you look at Fluent Validation to take care of your view model validations.
I hope this helps.
UPDATED ANSWER
The service that was used to get all the categories could look like this:
public class CategoryService : ICategoryService
{
private readonly ICategoryRepository categoryRepository;
public CategoryService(ICategoryRepository categoryRepository)
{
// Check if category repository is not null, throw exception if it is
this.categoryRepository = categoryRepository;
}
public IEnumerable<Category> GetAllCategories()
{
return categoryRepository.GetAllCategories();
}
}
categoryRepository is injected by Autofac.
Category service interface:
public interface ICategoryService
{
IEnumerable<Category> GetAllCategories();
}
I currently still use Entity Framework 4.1 code first.
My category repository:
public class CategoryRepository : ICategoryRepository
{
MyContext db = new MyContext();
public IEnumerable<Category> GetAllCategories()
{
return db.Categories
.OrderBy(x => x.Name);
}
}
My category repository interface:
public interface ICategoryRepository
{
IEnumerable<Category> GetAllCategories()
}
public class Test
{
rentalDB db = new rentalDB();
public Product LoadProductById(int pId)
{
return db.Products.Include(p => p.Model).Include(p => p.Category).Where(p => p.productId == pId).SingleOrDefault();
} // To get specific product.
public IEnumerable<Product> LoadAllProducts()
{
return db.Products.Include(p => p.Model).Include(p => p.Category).ToList();
} // To get all products.
}
I have changed your DbSet to Products make it more clear. This is how you load all the references for one product or all products, in order to iterate over them.

How can I get the values from a ListBox in my ASP.NET MVC 3 controller?

Here is my Item class:
public class Item
{
public int ItemId { get; set; }
public string Name { get; set; }
public virtual List<Tag> Tags { get; set; }
}
Here's my GET action:
//
// GET: /Home/AddItem/
public ActionResult AddItem()
{
List<Tag> Tags = Db.Tags.ToList();
ViewBag.Tags = new SelectList(Tags, "TagId", "Name");
return View();
}
Here's my view:
#model MySite.Models.Item
#using (Html.BeginForm()) {
//...
#Html.ListBox("Tags")
//...
}
Finally, here's my POST action:
//
// POST: /Home/AddItem/
[HttpPost]
public ActionResult AddItem(Item Item)
{
//...
List<Tag> NewItemTags = Item.Tags.ToList();
//...
}
The problem is that Item.Tags.ToList() is always empty in the POST action... like the selected values of the ListBox aren't being sent at all.
Stuck here. Please help.
I am assuming that TagId is integer.
public class Item
{
public int ItemId { get; set; }
public string Name { get; set; }
public virtual List<int> Tags { get; set; }
}
[HttpPost]
public ActionResult AddItem(Item Item)
{
List<int> NewItemTags = Item.Tags.ToList();
}
Also in View your ListBox should have Name = "Tags". If you are using ListBoxFor then no need to worry.
If still issue provide further information related to view.

Creating Dropdown List in MVC3

I am trying to create a dropdown list to display all the value in a custom collection class
such as
public class MyCustomClassCollection
{
public List<MyCustomClass> {get;set;}
}
I want it to show the Description:string of each MyCustomClass
I tried
<%: Html.DropDownList "Description", MyCustomClass %>
Resharper suggests that I cast MyCustomClass to IEnemerable
but the server returns an unable to cast error.
Any Idea how I can create this DropDownList?
__Modification___
public class ViewModel
{
public Detail detail { get; set; }
}
public class Detail //Inherited from webservce
{
public CustomClassCollection {get;set;}
.... Other Properties, a.k.a Custom Classes
}
public class CustomClassCollection
{
public List<CustomClass> {get;set;}
}
public class CustomClass {
public int Id {get;set;}
public string Description{get;set;}
... other properties
}
public ActionResult Index(int? id, DateTime? date)
{
if (id.Equals(null))
id = ######### ;
if (date.Equals(null))
date = DateTime.Today;
var vm = new ViewModel
{
Detail = _repository.Detail((int)id,(DateTime)date)
};
return View(vm);
}
The second argument of the DropDownList helper must be an IEnumerable<SelectListItem> or a SelectList which implements this interface for that matter. So in your controller action organize in such a way that you convert your custom collection into an IEnumerable<SelectListItem>. As always you could start by writing a view model:
public class MyViewModel
{
public string SelectedDescription { get; set; }
public SelectList Descriptions { get; set; }
}
and then have your controller action query the custom list and populate the view model which will be passed to the view:
public ActionResult Index()
{
var descriptions = yourCustomCollection.MyCustomClass.Select(x => new
{
Value = x.Description,
Text = x.Description
});
var model = new MyViewModel
{
Descriptions = new SelectList(descriptions, "Value", "Text")
};
return View(model);
}
and finally in your strongly typed view:
<%= Html.DropDownListFor(x => x.SelectedDescription, Model.Decriptions) %>
UPDATE:
After posting your updated models (which by the way are still incomplete and impossible to compile as you haven't provided any property names), here's an example:
public class ViewModel
{
public int SelectedId { get; set; }
public Detail Detail { get; set; }
}
public class Detail
{
public CustomClassCollection MyCollection { get; set; }
}
public class CustomClassCollection
{
public List<CustomClass> CustomClass { get; set; }
}
public class CustomClass
{
public int Id { get; set; }
public string Description { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index()
{
var vm = new ViewModel
{
Detail = new Detail
{
MyCollection = new CustomClassCollection
{
CustomClass = new List<CustomClass>
{
new CustomClass
{
Id = 1,
Description = "description 1",
},
new CustomClass
{
Id = 2,
Description = "description 2",
},
new CustomClass
{
Id = 3,
Description = "description 3",
},
}
}
}
};
return View(vm);
}
}
and in the view:
<%= Html.DropDownListFor(
x => x.SelectedId,
new SelectList(Model.Detail.MyCollection.CustomClass, "Id", "Description")
) %>
What you have to understand in order to define a dropdown list in ASP.NET MVC ius that you need 2 things:
A scalar property to bind the selected value to (SelectedId in my example)
A collection to bind the list to (Model.Detail.MyCollection.CustomClass in the example)

Resources