I have DropDownList that read fils from my database and show this files in my DropDownList.
The current solution is show on my DropDownListItem System.Web.Mvc.SelectList instead of my Object property. I want to include a drop down list of my object (read from database) across my webpage.
This is my object:
public class MyObject
{
public int id { get; set; }
public string fileName { get; set; }
public string browser { get; set; }
public string protocol { get; set; }
public string family { get; set; }
}
My controller:
public ActionResult Index()
{
List<MyObject> list = db.MyObjects.Where(x => x.family == "Web").ToList();
ViewBag.Files = new SelectList(list, "Id", "protocol");
return View();
}
I also try:
List<MyObject> list = db.Captures.Where(x => x.family == "Web")
.DistinctBy(y => y.protocol)
.ToList();
Index.cshtml
#Html.DropDownList("File", new SelectList(ViewBag.Files), "Select webmail site", new { style = "vertical-align:middle;" })
What i want to see in my DropDownList is my protocol property.
All the above not help and all i can see all the time is System.Web.Mvc.SelectList
Change your controller to:
public ActionResult Index()
{
ViewBag.Files = db.MyObjects.Where(x => x.family == "Web").ToList();
return View();
}
and your Index.cshtml
#Html.DropDownList("File", new SelectList(list, "Id", "protocol"), "Select webmail site", new { style = "vertical-align:middle;" })
Related
I have this function that will be called in the controller:
public EditViewModel PostEditViewModel(EditViewModel model)
{
using (var db = new NorthwindEntities())
{
var prod = db.Products.Where(x => x.Id == model.Id).Single();
{
prod.Id = model.Id;
...
//I need something like this:
//prod.CategoryID = model.CategoryList.CatId
//but obviously intellisense tells me that after the dot of CategoryList, only methods of that list can be called.
db.SaveChanges();
}
and this is my ViewModel:
public int Id{ get; set; }
...
public IEnumerable<Categories> CategoryList { get; set; }
public class Categories {
public int ProdId { get; set; }
public int? CatId { get; set; }
public string CatName { get; set; }
}
how do I call the CategoryList through my EditViewModel so that I can edit the Category of a specific product through HTML.DropdownList?
If your product model have CategoryId property (I just can't see it in your question) and you using strongly typed View You always can use this overload of DropDownListBoxFor() helper:
#Html.DropDownListFor(
x => x.CategoryId,
new SelectList(Model.CategoryList, "CatId", "CatName")
)
But actually i recomend you to use SelectListItem in ViewModels for all your dropdowns, becouse it's really bad practice - put domain entity on your View
Than your ViewModel will be like:
public int Id { get; set; }
public int CategoryId { get; set; }
...
public IEnumerable<SelectListItem> CategoryList { get; set; }
And on the View you can do this way:
#Html.DropDownListFor(x => x.CategoryId, Model.CategoryList)
In your GET ViewModel Controller you can initialize your CategoryList like this:
model.CategoryList = db.Categories.OrderBy(x => x.Name)
.Select(x => new SelectListItem
{
Text = x.Name,
Value = x.Id.ToString()
});
It really helps you to get your Views cleaner.
It looks like CategoryList is used to populate the items in your DropDownList, and CatId is the property on your view model that captures the ID value of the selected category.
If that is the case, you can just assign it like so:
if (model.CatId.HasValue)
{
prod.CategoryID = model.CatId.Value;
}
If I not mistaken and I understood you, you should to create class EditViewModel in this class create the fields:
public int Id{ get; set; }
...
public IEnumerable<Categories> CategoryList { get; set; }
Next, in your controller, you should use the following code:
var prod = db.Products.Where(x => x.Id == model.Id).Single();
{
prod.Id = model.Id;
...
prod.CategoryID = model.CategoryList.Select(m => m.CatId)
//but Select returned the List of CatId, I suggest thet prod.CategoryID is List
}
db.SaveChanges();
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)
...
hi all i have a controller
public ActionResult Search(FormCollection collection)
{
....
var column = new Models.ColumnMapping("CTR");
ViewData["ColoumName"] = column;
var search = new Models.Search(columnname,searchvalue);
return View(search);
}
my view data contains following model property value..
public class Column {
public string ColumnName { get; set; }
public DataTypes DataType { get; set; }
}
i have to create a drop down list for ColumnName(all data contain in VIewData) and my view is like
#Html.DropDownListFor("clname", ViewData["ColoumName"] as IEnumerable<AML.Web.Models.Column>, "ColumnName", "ColumnName"))
but this is not working
Try like this, This is just an example.
View
#Html.DropDownList("CustomerId", (SelectList)ViewBag.CustomerNameID, "--Select--")
Controller
public ActionResult CustomerInfo()
{
ViewBag.CustomerNameID = new SelectList(new[]
{
new {ID="1",Name="name1"},
new{ID="2",Name="name2"},
new{ID="3",Name="name3"},
},"ID", "Name");
return View();
}
Model
public Class ViewModel {
public int CustomerId { get; set; }
}
If you have to use #Html.DropDownListFor then it should like this #Html.DropDownListFor(m => m.CustomerId ,(List<SelectList>)ViewBag.CustomerNameID,"-- Select --", new { #class = "input-block-level" })
instead of DropDownListFor try DropDownList with SelectList().
#Html.DropDownList("clname",
new SelectList((IEnumerable) ViewData["ColoumName"], "Id", "ColoumName"))
I am working on an MVC4 Project and I'm looking to add a search by dropdown menu so that the user can select different variables to search through.
My Model
public class BloodStoredModel
{
[Required]
public int ID { get; set; }
[Required]
[DisplayName("Blood Type")]
public string bloodType { get; set; }
[Required]
[DisplayName("RH Factor")]
public string rhFactor { get; set; }
[Required]
[DisplayName("Last Name")]
public string donorLastName { get; set; }
[Required]
[DisplayName("First Name")]
public string donorFirstName { get; set; }
[Required]
[DisplayName("Address")]
public string address { get; set; }
[Required]
[DisplayName("Phone #")]
public string telephoneNumber { get; set; }
public class BloodDBContext : DbContext
{
public DbSet<BloodStoredModel> BloodStored { get; set; }
}
}
Here is my Controller method
public ActionResult SearchIndex(string searchString)
{
//string searchString = id;
var list = new SelectList(new[]
{
new{ID="1",Name="bloodType"},
new{ID="2",Name="rhFactor"},
new{ID="3",Name="donorLastName"},
new{ID="4",Name="donorFirstName"},
new{ID="5",Name="address"},
new{ID="6",Name="telephoneNumber"}
},
"ID", "Name", 1);
ViewData["list"] = list;
var bloodSearch = from m in db.BloodStored
select m;
if (!String.IsNullOrEmpty(searchString))
{
//bloodSearch = bloodSearch.Where(s => s.donorLastName.Contains(searchString));
bloodSearch = list.Select((value, index) => new { value, index })
.Where(s => s.value.Contains(searchString))
.Select(s => s.index);
}
return View(bloodSearch);
}
The commented lambda expression works but only for that certain variable. What I would like to do is have that be selectable dynamically through a dropdown list.
Here is my relevant view
#using (Html.BeginForm()){
<p> #Html.DropDownList("list", ViewData["list"] as SelectList)
#Html.TextBox("SearchString")<br />
<input type="submit" value="Filter" /></p>
}
The reason the value is not changing in the backend is because you are using DropDownList instead of DropDownListFor. DropDownListFor will automatically bind the selection to your model once the submit button is pressed (POST is executed). You are going to have to include the drop down list in a ViewModel or tweak your front end using JavaScript/Jquery.
EDIT
You would have to create a new class:
public DropDownOption
{
public int Id {get; set;}
public string Description {get; set;}
}
create a ViewModel:
public myViewModel
{
public List<DropDownOption> DropDownOptions {get; set;}
public int OptionSelected {get; set;}
}
Controller:
{
//other stuff
var myVM = new myViewModel();
myVM.DropDownOptions = new List<DropDownOption>(){
new DropDownOption{Id = 1, Name = "bloodType"},
new DropDownOption{Id = 2, Name = "rhFactor"},
//etc.
}
View:
#model .myViewModel
//other stuff
#Html.DropDownListFor(m => m.OptionSelected,
Model.DropDownOptions.Select(option => new SelectListItem
{
Text = option.Description,
Value = option.Id
})
To search the array of BlookSearchModel using a property selected by the user you would need to use reflection. Add the following function.
private string GetValue(BloodStoredModel obj, string propertyName)
{
Type type = typeof(BloodStoredModel);
if (type != null)
{
PropertyInfo property = type.GetProperty(propertyName);
if (property != null)
{
return (string)property.GetValue(obj);
}
}
return null;
}
You can then you it like this
bloodSearch = models.Where(s => string.Compare(GetValue(s, propertyName), searchString) == 0);
Of course there is a potential for errors by hard coding the property names. You could use reflection to enumerate the property names.
ViewBag.SearchFields = from prop in properties
select new SelectListItem() { Text = prop.Name };
This would also select the Id field from your model. However, you can modify the linq statement to exclude it.
EDIT I added the following. Plus I changed the above code to use ViewBag instead of ViewData.
To have your view use this you can do this.
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "form1" }))
{
#Html.DropDownList("SearchFields")
<input type="submit" value="submit" onclick="return SetAction();" />
}
<script>
function SetAction() {
form = document.getElementById("form1");
dropdown = document.getElementById("SearchFields");
form.action = "/" + "?searchString=" + dropdown.value;
return true;
}
</script>
I have following SelectList declaration in CourseRegisterModel:
public class CourseRegisterModel
{
public StudentModel Student { get; set; }
public CourseModel Course { get; set; }
public IEnumerable<SelectListItem> CoursesList { get; set; }
public DateTime RegisterDate { get; set; }
}
In CourseController I am retrieving all available courses by calling wcf web service:
public ViewResult Index()
{
ServiceCourseClient client = new ServiceCourseClient();
Course[] courses;
courses = client.GetAllCourses();
List<CourseModel> modelList = new List<CourseModel>();
foreach (var serviceCourse in courses)
{
CourseModel model = new CourseModel();
model.CId = serviceCourse.CId;
model.Code = serviceCourse.Code;
model.Name = serviceCourse.Name;
model.Fee = serviceCourse.Fee;
model.Seats = serviceCourse.Seats;
modelList.Add(model);
}
return View(modelList);//RegisterCourses.chtml
}
I need to populate these courses in a dropdown on view RegisterCourses.chtml. How to put all records in selectlist in above code? Also how would i use that selectlist on view?
For starters, your RegisterCourses.cshtml needs to use:
#model <namespace>.CourseRegisterModel
Then, your controller code would be:
public ViewResult Index()
{
ServiceCourseClient client = new ServiceCourseClient();
Course[] courses;
courses = client.GetAllCourses();
CourseRegisterModel model = new CourseRegisterModel();
//model = other model population here
model.CourseList = courses.Select(sl => new SelectListItem()
{ Text = sl.Name,
Value = sl.CId })
.ToList();
return View(model);
}
And finally, back to your view (RegisterCourses.cshtml) - it should contain:
#Html.DropDownListFor(m => m.Course.CId, Model.CourseList)
Use the Html.DropDownList method: http://msdn.microsoft.com/en-us/library/dd492738(v=vs.108).aspx
Pass in the desired name of the drop down list as first argument, as second argument pass in your CourseList:
#Html.DropDownList("CoursesList", Model.CoursesList)