i have a table in my database which i select all rows to fill it in my dropdownlist in my view.
i canĀ“t understand how can i fill the values in there.
someone can give me a hand?
My code:
Model:
public class MyList
{
public int id { get; set; }
public string name{ get; set; }
}
public class Empresas
{
public static IEnumerable<MyList> Getmyinformation()
{
var list = new List<MyList>();
string connection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (var con = new SqlConnection(connection))
{
con.Open();
using (var command = new SqlCommand("SELECT * FROM mytable", con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string Name= reader[1] as string;
list.Add(new MyList() { name= Name});
}
}
con.Close();
}
return list;
}
}
public class DefaultConnection : DbContext
{
public DbSet<MyList> lat { get; set; }
}
Controller:
private DefaultConnection db = new DefaultConnection();
public ActionResult Add()
{
return View(db.lat.ToList());
}
View:
#Html.DropDownListFor("-- Select --", new SelectList("")) <=== ???? i dont know
Simply in controller type:
ViewBag.CategoryList = new SelectList(db.Categories.ToList(), "Id", "Name");
And in view write:
#Html.DropDownListFor(model => model.CategoryId, ViewBag.CategoryList as IEnumerable<SelectListItem>, new { #class = "anyclass" })
In my practice I create dropdownlist as follow:
first I create view model
public class MyObj
{
public int id { get; set; }
public string name{ get; set; }
}
// viewmodel
public class MyviewModel
{
public IQuerable<MyObj> MyObjs{get;set;}
public Other Other{get;set;}
}
then I pass this model from controller to view
private DefaultConnection db = new DefaultConnection();
public ActionResult Index()
{
var drop = new MyviewModel
{
MyObjs = db.MyObjs,// selecting table...
Other = new Other
}
return View(drop);
}
in Controller
#Html.DropDownListFor(model => model.Other.MyObjId, new SelectList(Model.MyObjs , "id", "name","--select--"))
Try this,
View :-
#Html.DropDownListFor(m => m.CustomerId, Model.customerNameList, "--Select--")
Controller:-
public ActionResult CustomerInfo()
{
var List = GetCustomerName();
ViewBag.CustomerNameID = new SelectList(List, "CustomerId", "customerName");
ViewBag.RegisterItems = GetAllRegisterData();
return View();
}
public List<CustomerModel> GetCustomerName()
{
// Customer DropDown
using (dataDataContext _context = new dataDataContext())
{
return (from c in _context.Customers
select new CustomerModel
{
CustomerId = c.CID,
customerName = c.CustomerName
}).ToList<CustomerModel>();
}
}
Model:
public class CustomerModel
{
public int CustomerId { get; set; }
[StringLength(9), Required, DisplayName("Social security number")]
[RegularExpression(#"\d{3}-\d\d-\d{4}", ErrorMessage = "Invalid social security number")]
public string customerName { get; set; }
public List<MyListItems> customerNameList { get; set; }
}
Create a ViewModel like this:
public class ListViewModel
{
public MyList MyList { get; set; }
public int SelectedId { get; set; }
}
Then, change your Action to this:
public ActionResult Add()
{
var viewModel = new ListViewModel { MyList = db.lat.ToList() };
return View(viewModel);
}
And, then, this is what you will have in your View:
#model MyApp.ViewModels.ListViewModel
#Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.MyList as IEnumerable, "Id", "Name"))
Related
I got a two DropDownList's in View. When i try pass those parameters, method in controller called but parameters equals a null.
When i check in browser (F12-network) i watch parameters - they are sended but in method still nulls
P.S.
I try change type of parameters on List or Location and JobTitle or CommonEntity, but its doesn't work
Controller:
public class HelloController: Controller
{
[HttpGet]
public IActionResult Index()
{
var locations = new List<Location>()
{
new Location()
{
Id = 0,
Title = "Russia"
},
new Location()
{
Id = 1,
Title = "Canada"
}
};
ViewBag.Location = locations;
var jobs = new List<JobTitle>()
{
new JobsTitle()
{
Id = 0,
Title = "Manager"
} ,
new JobsTitle()
{
Id = 1,
Title = "Programmer"
}
};
ViewBag.JobTitle = new SelectList(jobs, "Title", "Title");
return View();
}
[HttpPost]
public string Find(string answer1, string answer2)
{
return "Fine";
}
View:
#using Stargate.Core.Models.CoreEntities
#model CommonEntity
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.Location.Title, new SelectList(ViewBag.Location, "Title", "Title"))
#Html.DropDownListFor(m => m.JobTitle.Title, new SelectList(ViewBag.JobTitle, "Title", "Title"))
<button type="submit">Find</button>
}
Models:
public class CommonEntity
{
public Location Location { get; set; }
public JobTitle JobTitle { get; set; }
}
public class JobTitle
{
public long Id { get; set; }
public string Title { get; set; }
}
public class Location
{
public long Id { get; set; }
public string Title { get; set; }
}
Because the parameter names you accept are answer1, answer2, you should have a matching name in your view to make it possible to bind successfully.
You can modify your front-end code as follows(DropDownListForto DropDownList):
#model CommonEntity
#using (Html.BeginForm("Find", "Hello"))
{
#Html.DropDownList("answer1", new SelectList(ViewBag.Location, "Title", "Title"))
#Html.DropDownList("answer2", new SelectList(ViewBag.JobTitle, "Title", "Title"))
<button type="submit">Find</button>
}
Your Controller:
public class HelloController : Controller
{
[HttpGet]
public IActionResult Index()
{
var locations = new List<Location>()
{
new Location()
{
Id = 0,
Title = "Russia"
},
new Location()
{
Id = 1,
Title = "Canada"
}
};
ViewBag.Location = locations;
var jobs = new List<JobTitle>()
{
new JobTitle()
{
Id = 0,
Title = "Manager"
} ,
new JobTitle()
{
Id = 1,
Title = "Programmer"
}
};
ViewBag.JobTitle = jobs;
return View();
}
[HttpPost]
public string Find(string answer1,string answer2)
{
return "Fine";
}
}
Class:
public class CommonEntity
{
public Location Location { get; set; }
public JobTitle JobTitle { get; set; }
}
public class JobTitle
{
public long Id { get; set; }
public string Title { get; set; }
}
public class Location
{
public long Id { get; set; }
public string Title { get; set; }
}
Result:
you are doing things wrongly,
you should correct your cshtml so that when submitting the form, it will target your Find Action,
#using (Html.BeginForm("Find", "Hello"))
In your Find Action you should provide in input args resolvable by the DefaultModelBinder, since you don't have a ViewModel to intercept the response, I would suggest that you recieve a FormCollection and you can access your values from there.
[HttpPost]
public string Find(FormCollection form)
{
return "Fine";
}
Try updating parameters as below. Please refer Model Binding in ASP.NET Core for more details.
[HttpPost]
public string Find(Location Location, JobTitle JobTitle)
{
return "Fine";
}
Or you can try with parameter of CommonEntity like below.
[HttpPost]
public string Find(CommonEntity commonEntity)
{
var locationTitle = commonEntity.Location.Title;
var jobTitle = commonEntity.JobTitle.Title;
return "Fine";
}
I am trying to add some values into my SelectList data member in my object but I get an error
public ActionResult Create()
{
var paf = new ProductAddForm();
paf.Sizes = new SelectList(m.GetProductSizes());
paf.Suppliers = new SelectList(m.GetAllSuppliersList(), "Id", "Name");
return View(paf);
}
that is my creat function, and the paf.Sizes / paf.Suppliers code does not work.
My productaddform class:
public class ProductAddForm
{
public double MSRP { get; set; }
public string Name { get; set; }
public string ProductId { get; set; }
public ICollection<SelectList> Sizes { get; set; }
public ICollection<SelectList> Suppliers { get; set; }
public string UPC { get; set; }
}
And my methods in my manager.cs
public IEnumerable<SupplierList> GetAllSuppliersList()
{
var fetchedObjects = ds.Suppliers.OrderBy(n => n.Name);
var Suppliers = new List<SupplierList>();
foreach (var item in fetchedObjects)
{
var s = new SupplierList();
s.Name = item.Name;
s.Id = item.Id;
Suppliers.Add(s);
}
return (Suppliers);
}
public List<string> GetProductSizes()
{
return new List<string>() { "Small", "Medium", "Large" };
}
Whats wrong?
Suppliers is a collection of SelectList. So you need to Add item into the collection
Change
paf.Suppliers = new SelectList(m.GetAllSuppliersList(), "Id", "Name");
to
paf.Suppliers.Add(new SelectList(m.GetAllSuppliersList(), "Id", "Name"));
I have a Create page that have a Dropdownlist with Players
This I populate in my controller
[HttpGet]
public ActionResult Create()
{
var vm = new CreateMatchViewModel
{
Winner =
CreateWinnerList(),
PlayerList = CreatePlayerList()
}
;
return View(vm);
}
private IEnumerable<SelectListItem> CreatePlayerList()
{
List<Player> playerList = _playerManagementRepository.GetAllPlayers();
return playerList.Select(p => new SelectListItem
{
Text = p.Username,
Value = p.Id.ToString()
});
}
private SelectListItem[] CreateWinnerList()
{
return new[]
{
new SelectListItem {Text = "Player 1", Value = 1.ToString(), Selected = true}
, new SelectListItem {Text = "Player 2", Value = 2.ToString(), Selected = false}
};
}
This populates my view fine
#model TableTennis.ViewModels.CreateMatchViewModel
#{
ViewBag.Title = "Enter Match Result";
}
#using (Html.BeginForm("Create", "Match", FormMethod.Post))
{
<h4>Player 1</h4>
#Html.DropDownListFor(p => p.Player1ID, Model.PlayerList)
<h4>Player 2</h4>
#Html.DropDownListFor(p => p.Player2ID, Model.PlayerList)
<h4>Winner</h4>
#Html.DropDownListFor(w => w.WinnerID, Model.Winner)
<h5>Set 1</h5>
#Html.EditorFor(p => p.Score1Set1)
#Html.EditorFor(p => p.Score2Set1)
<h5>Set 2</h5>
#Html.EditorFor(p => p.Score1Set2)
#Html.EditorFor(p => p.Score2Set2)
<h5>Set 3</h5>
#Html.EditorFor(p => p.Score1Set3)
#Html.EditorFor(p => p.Score2Set3)
<input type="submit" value="Add result" />
}
Then on Post I do some validation where ModelState is not valid, so the following is run
[HttpPost]
public ActionResult Create(CreateMatchViewModel vm)
{
try
{
if (!ModelState.IsValid)
{
vm.PlayerList = CreatePlayerList();
vm.Winner = CreateWinnerList();
return View(vm);
}
But this fails follwing error, but I am not sure how to cast the Guid to a SelectedListItem so that the same item in the list is selected again on the new Get request
The ViewData item that has the key 'Player1ID' is of type 'System.Guid' but must be of type 'IEnumerable'.
ViewModel
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace TableTennis.ViewModels
{
public class CreateMatchViewModel
{
public CreateMatchViewModel()
{
Score1Set1 = 0;
Score1Set2 = 0;
Score1Set3 = 0;
Score2Set1 = 0;
Score2Set2 = 0;
Score2Set3 = 0;
}
public IEnumerable<SelectListItem> PlayerList { get; set; }
public IEnumerable<SelectListItem> Winner { get; set; }
[Required]
public Guid Player1ID { get; set; }
[Required]
public Guid Player2ID { get; set; }
[Required]
public int WinnerID { get; set; }
[Required]
[RegularExpression("[0-9][0-9]?")]
public int Score1Set1 { get; set; }
[RegularExpression("[0-9][0-9]?")]
[Required]
public int Score1Set2 { get; set; }
[RegularExpression("[0-9][0-9]?")]
[Required]
public int Score1Set3 { get; set; }
[RegularExpression("[0-9][0-9]?")]
[Required]
public int Score2Set1 { get; set; }
[RegularExpression("[0-9][0-9]?")]
[Required]
public int Score2Set2 { get; set; }
[RegularExpression("[0-9][0-9]?")]
[Required]
public int Score2Set3 { get; set; }
}
}
EDIT
This made it work
if (!ModelState.IsValid)
{
ModelState.Clear();
vm.PlayerList = CreatePlayerList();
vm.Winner = CreateWinnerList();
return View(vm);
}
if (vm.Player1ID == vm.Player2ID)
{
ModelState.Clear();
vm.PlayerList = CreatePlayerList();
vm.Winner = CreateWinnerList();
return View(vm);
}
Original answer:
Problem is that in your CreatePlayerList() method you are casting the id to a string so MVC is unable to get the selected item based on the id in your model, which is a guid. Player1ID and Player2ID need to be strings in your ViewModel, no matter what you do with them in your database.
Actual answer, fished out of the comments:
The problem, despite the text of the error message is NOT that Player1ID needs to be IEnumerable or IEnumerable but that the list is gone from the model, or the list does not contain the ID. You (may) need to examine the ViewModel when ModelState is not valid and determine what is not valid and why. You may have to use ModelState.Remove() along with reconstructing what is faulty in your Model.
I have this problem where i want to make 7 dropdowns for each day of the week.
In each one of those dropdowns i wish to add the same data.
My ViewModel:
public class WeekDienstCreateViewModel
{
public WeekDienst weekDienst {get; set;}
public List<DienstPerWeekDienst> diensten { get; set; }
public WeekDienstCreateViewModel() { }
}
My Create Method in Controller:
As u can see I add everything allready except DienstId which is want to add with my dropdowns.
public ActionResult Create(int id)
{
WeekDienst wd = _service.FindWeekDienst(id);
WeekDienstCreateViewModel vm = new WeekDienstCreateViewModel();
vm.diensten = new List<DienstPerWeekDienst>();
vm.weekDienst = wd;
for (int i = 1; i <= 7; i++)
{
DienstPerWeekDienst dpwd = new DienstPerWeekDienst();
dpwd.volgnummer = i;
dpwd.WeekDienstId = wd.Id;
vm.diensten.Add(dpwd);
}
ViewBag.Diensten = _service.DienstenList(wd.AfdelingId);
return View(vm);
}
Classes:
public class DienstPerWeekDienst
{
[Key]
public int Id { get; set; }
[Required]
public int WeekDienstId { get; set; }
[Required]
public int DienstId { get; set; }
[Required]
[Range(1, 7)]
public int volgnummer { get; set; }
[ForeignKey("WeekDienstId")]
public virtual WeekDienst WeekDienst { get; set; }
[ForeignKey("DienstId")]
public virtual Dienst Dienst { get; set; }
public virtual ICollection<WeekDienst> WeekDiensten { get; set; }
}
public class WeekDienst
{
[Key]
public int Id { get; set; }
[Required]
public int AfdelingId { get; set; }
[Required]
[StringLength(5, ErrorMessage = "Value for {0} cannot exceed {1} characters.")]
[RegularExpression(#"^[a-zA-Z0-9]{5}$", ErrorMessage = "Verplicht 5 cijfers lang.")]
public string code { get; set; }
[DisplayName("Template")]
public bool template { get; set; }
[ForeignKey("AfdelingId")]
public virtual Afdeling Afdeling { get; set; }
}
And in my view i wish to create 7 dropdowns where i put in all my "Diensten" (class Dienst, fk in DienstPerWeekDienst). When I choose 1 i wish to add the "DienstId" into the "DienstPerWeekDienst" class.
So in my View i got this:
#foreach (var day in Model.diensten)
{
var currentDay=day;
#Html.DropDownListFor(currentDropDown=>currentDay, new SelectList(ViewBag.Diensten, "Value", "Text"))
}
I Wish to postback the chosen "Diensten" and create the "WeekDienst" but now i am just posting a null "DienstPerDienstWeekCreateViewModel". How am I able to fix this?
Thanks in Advance
FIX (Thanks to Siva Gopal)
I fixed this by doing:
#for (int i = 0; i < #Model.diensten.Count; i++)
{
#Html.HiddenFor(m => (m.diensten[i].volgnummer))
#Html.HiddenFor(m => (m.diensten[i].WeekDienstId))
#Html.DropDownListFor(m=> (m.diensten[i].DienstId), new SelectList(ViewBag.Diensten, "Value", "Text"))
}
You may try using
#foreach (var day in Model.diensten)
{
var currentDay=day;
#Html.DropDownListFor(currentDropDown=>currentDay, new SelectList(ViewBag.Diensten, "PropertyName_Holding_Value", "PropertyName_Holding_DisplayText"), new { })
} //This uses the Lambda Expression. Your dropdown Name/Id would be 1,2,3 etc. based on currentDay value.
OR
#foreach (var day in Model.diensten)
{
var currentDay=day;
var dropdownName=string.Format("diensten[{0}]",day-1); //If you want to model bind the selected dropdown value to input entity in POST request. The final dropdownName format should match the hierarchy of the property inside input entity/object. Even without this name formation, you can still POST the selected value back using Jquery/Javascript.
#Html.DropDownList(dropdownName, new SelectList(ViewBag.Diensten, "PropertyName_Holding_Value", "PropertyName_Holding_DisplayText"), new {})
} //
Note for Value Post back/model bind on full Page submit:
To be able to model bind/POST back values to the server, the html element names corresponding to the properties should be rendered as follows: Suppose if you display Employee.Department.Name, then name of textbox, displaying the Department Name in View should match Department_ReferenceName_Inside_Employee.Name for model binding.
Model:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string City { get; set; }
public Department EmpDepartment { get; set; }
public List SubOrdinates { get; set; }
}
public class Department
{
public string Name { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
//Prepare the model and send it to the view
Employee emp = new Employee { EmpDepartment = new Department { Name = "IT" } };
emp.SubOrdinates = new List<Employee> { new Employee { Name = "Emp1" }, new Employee { Name = "Emp2" } };
return View(emp);
}
[HttpPost]
public ActionResult Index(Employee emp)
{ //Put a break-point here and see how the modified values in view are flowing into emp..
return View(emp);
}
public ActionResult About()
{
return View();
}
}
View:
#model MvcApplication.Models.Employee
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.EmpDepartment.Name)
#Html.LabelForModel("SubOrdinates :")
for (int i = 0; i < #Model.SubOrdinates.Count; i++)
{
#Html.TextBoxFor(m => (m.SubOrdinates[i].Name))
}
<input type="submit" name="name" value="Submit" /> }
ViewSource/PageSource:
The above text box syntax will be rendered as :
<input id="EmpDepartment_Name" name="EmpDepartment.Name" type="text" value="IT" /> <!--See above html : name=EmpDepartment.Name -->
<label for="">SubOrdinates :</label>
<input id="SubOrdinates_0__Name" name="SubOrdinates[0].Name" type="text" value="Emp1" />
<input id="SubOrdinates_1__Name" name="SubOrdinates[1].Name" type="text" value="Emp2" /> <!--See above html for how collection item Name(s) are being renderd by view engine-->
<input type="submit" name="name" value="Submit" />
#foreach (var day in Model.diensten)
{
var currentDay = day;
#Html.DropDownListFor(x => currentDay, new SelectList(ViewBag.Diensten, "Value", "Text"), new { #id = "DienstList" })
}
List<MvcApplication1.Models.Country> cntry = db.Countries.ToList();
SelectListItem sss = new SelectListItem();
List<SelectListItem> sltst = new List<SelectListItem>();
sss.Text = "Select";
sss.Value = "0";
sltst.Add(sss);
foreach (MvcApplication1.Models.Country s in cntry){
SelectListItem s1 = new SelectListItem();
s1.Text = s.Country1;
s1.Value = Convert.ToString(s.Id);
sltst.Add(s1);}
#Html.DropDownList("country", sltst, new { #id = "country" })
I hope I explain this correctly..
What I am trying to do is build up a session array with a list of products in.
Then display these on a form in text boxes with quantiles next to them and be able to submit them. I think I need to use template editor. But I don't know how to put data into the list of items.
This is how my session variable is currently being populated..
IList<EnqProduct> items2 = Session["enquiry"] as IList<EnqProduct>;
desc = desc.Replace(",", "");
EnqProduct item = new EnqProduct();
item.Id = (items2.Count + 1).ToString();
item.Product = desc;
item.Quantity = "0";
items2.Add(item);
So desc, can be productone, product two etc.
Enquiry Product model:
namespace MvcEditorTemplates.Models
{
public class EnqProduct
{
public string Id { get; set; }
public string Product { get; set; }
public string Quantity { get; set; }
}
}
Normal Enquiry Model:
public class Enquiry
{
public List<EnqProduct> EnqProduct { get; set; }
}
How i am trying to populate the model, but this is static. I need it to be populated from the array items:
var EnquiryModel = new Enquiry {
EnqProduct = items2.Select(c => new EnqProduct()
{
Quantity = c.Quantity,
Product = c.Product
})
};
Enquiry product template view:
#model MvcEditorTemplates.Models.EnqProduct
<div class="fl">
<p>
#Html.LabelFor(x => x.Product)
#Html.TextBoxFor(x => x.Product)
</p>
<p>
#Html.LabelFor(x => x.Quantity)
#Html.TextBoxFor(x => x.Quantity)
</p>
</div>
This is how im trying to get it to be displayed din the view:
#Html.EditorFor(model => model.EnqProduct)
EDIT:
at items2.Select(c => new EnqProduct()
i get a IEnumerbale error something about cast?
Try something like this:
public class ErrorMessage
{
public DateTime ErrorDate { get; set; }
public string ErrorText { get; set; }
public int DexRowId { get; set; }
}
public class Transaction
{
public string TransactionType { get; set; }
public string Processed { get; set; }
public DateTime UpdateDate { get; set; }
public int DexRowID { get; set; }
public string Text { get; set; }
}
public class Result
{
public List<ErrorMessage> errorMessageList { get; set; }
public List<Transaction> transactionList { get; set; }
}
In your controller:
List<Transaction> transactionList = ...;//query to populate your list;
List<ErrorMessage> errorMessageList = ...;//query to populate your list;
Result result = new Result();
result.ErrorMessageList = errorMessageList;
result.TransactionList = transactionList;
return View(result);
and in your view:
#model Models.Result
#{
ViewBag.Title = "Result";
Layout = "~/Views/Shared/_ResultLayout.cshtml";
}
EDIT:
#model IENumerable<MvcEditorTemplates.Models.EnqProduct>
#{
foreach( EnqProduct ep in #model)
{
.... your code comes here.........
}
}