This question already has answers here:
using DropdownlistFor helper for a list of names
(2 answers)
Closed 7 years ago.
I have just started developing using the MVC 5 design pattern, I'm trying to populate my DropDownList with data from the database, this is what I have in my Country model:
public class Country
{
public DataTable GetAllCountries()
{
string theSql = "SELECT * FROM Country";
IDataAccess dataAccess = new DataAccess();
return dataAccess.GetData(theSql);
}
}
Then within my controller I have:
public ActionResult Index()
{
List<SelectListItem> objResult = new List<SelectListItem>();
Models.Country country = new Models.Country();
DataTable result = country.GetAllCountries();
foreach(DataRow item in result.Rows)
{
SelectListItem temp = new SelectListItem();
temp.Value = item["id"].ToString();
temp.Text = item["country"].ToString();
objResult.Add(temp);
}
ViewBag.DropDownResult = objResult;
return View();
}
Then in my Partial view I have:
#model MyProject.Models.Country
#Html.DropDownListFor(ViewBag.DropDownResult as List<SelectListItem>)
Howvever on DropDownListFor I receieve this error:
No overload for method 'DropDownListFor' takes 1 arguments
Does anyone know what I am doing wrong? If I'm correctly following the MVC pattern also?
Thanks guys
You need to specify in which object is the property you want to display.
#Html.DropDownListFor requires atleast 2 parameters. The first should be the object and the second the list which containts the items.
Something like:
#model MyProject.Models.Country
#Html.DropDownListFor(m => m.SomeProperty, ViewBag.DropDownResult as List<SelectListItem>)
Related
I created a ViewData[] to populate a drop down list. There are 3 fields (Id, Grade and ClzName) in ViewData[]. I need to set ID field to Id and Value field to Grade+ClzName of the drop down list.
I try it as follows but failed. Any one can please help me to resolve it.
controller.cs
private void PopulateSelectClassDDL()
{
using (_context)
{
List<Class> classList = new List<Class>();
classList = _context.Classes.ToList();
ViewData["classList"] = classList;
}
}
view.cshtml
#Html.DropDownList("ClzId", new SelectList((System.Collections.IEnumerable)ViewData["classList"],"Id", "Grade" + "ClzName"))
Add a property to the model that returns what you want and use that
–by Sami Kuhmonen
Then I add following line into my model.
[NotMapped] public string className=> $"{Grade} {ClzName}"
This question already has answers here:
How to access values inside Hashtable list/Viewmode.Model and display in View?
(2 answers)
Closed 3 years ago.
This is how i insert value into a hashtable and these mid,mprize are model variables.I need to access it and display it on my View.I have tried a lot but i failed.
if (Session["cart"] != null)
{
Hashtable ht = (Hashtable)Session["cart"];
var mydata = new List<cart>
{
new cart { mid= mid, mprize = mrate },
};
//Hashtable ht = new Hashtable();
ht.Add(mid,mydata);
Session["Cart"] = ht;
}
this is what i have tried to get value
public ActionResult cart()
{
Hashtable ht = (Hashtable)Session["cart"];
Hashtable ht = (Hashtable)Session["cart"];
ViewBag.MyData = ht;
return View();
}
View
#foreach (var e in ViewData.Model)
{
//dont know how to fetch value from e
}
i just copied above code from google ,And am a newbie in hashtable
and How to bind this data with my model ?Because my view is using model binding.
I dont know how to put into my List using keys
Ihave value in the form
Method
public ActionResult cart()
{
Hashtable ht = (Hashtable)Session["cart"];
ViewBag.myData = ht;
return View();
}
View
#{
var items = ViewBag.myData;
*/your code for getting data using keys /*
}
foreach(var it in (List<cart>)ht["hashData"])
{
#it.mid
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to display data retrieved from a linq query in a view via a view model. I have a variable set to the linq query and then I am referencing it in an instance of the table in the view model. If I forgo the view model and just return the variable in the return view, I get my desired data. When I try to use the view model, I am forced to call ToString when I reference the linq query variable and instead of my desired result data, I get this TRAIntranet2019.Models.TblShiftInfo which is the table I am querying. And I am changing the model reference at the top of my view for either the view model (when using the view model) or the regular model (when using just the linq variable). Shift target is the current example I'm working on.
private TRAKERContext db = new TRAKERContext();
// GET: LandingPageVMs
public IActionResult Index()
{
var shiftTarget = db.TblShiftInfo.FirstOrDefault();
//var rvuvalue = db.Tradetail.FirstOrDefault().ToString();
TblShiftByRadByDate tblShiftByRadByDate = new TblShiftByRadByDate()
{
//ShiftName = "Late Night Shift"
};
Tradetail tradetail = new Tradetail()
{
//Rvuvalue = (double)rvuvalue
//SignLastName = rvuvalue.ToString()
};
TblShiftInfo tblShiftInfo = new TblShiftInfo()
{
//ShiftAvgTarget = Convert.ToDouble(shiftTarget),
Shift_Name = shiftTarget.ToString()
};
RadidCrosswalk radidCrosswalk = new RadidCrosswalk()
{
RadFname = "Jimmie"
};
FacilityCrosswalk facilityCrosswalk = new FacilityCrosswalk()
{
FacilityName = "TRA"
};
LandingPageVM vm = new LandingPageVM()
{
TblShiftByRadByDate = tblShiftByRadByDate,
Tradetail = tradetail,
TblShiftInfo = tblShiftInfo,
RadidCrosswalk = radidCrosswalk,
FacilityCrosswalk = facilityCrosswalk
};
return View(vm);
}
Expected output = "The name of the shift"
actual output = "TRAIntranet2019.Models.TblShiftInfo"
I don´t understand the question but try to figure out...
Using ViewModel:
The action on the controller:
public IActionResult About()
{
TblShiftInfo tblShiftInfo = new TblShiftInfo()
{
Shift_Name = "Shift Name Example",
ShiftAvgTarget = 12345
};
LandingPageVM vm = new LandingPageVM()
{
TblShiftInfo = tblShiftInfo,
};
return View(vm);
}
The view:
#model MyWevApp2.Models.LandingPageVM
<h2>Data in ViewModel</h2>
<p>#Model.TblShiftInfo.Shift_Name</p>
<p>#Model.TblShiftInfo.ShiftAvgTarget</p>
Using ViewBag or ViewData.
If you don´t want to use a ViewModel... you can use ViewBag or ViewData. For example:
Controller:
public IActionResult Contact()
{
TblShiftInfo tblShiftInfo = new TblShiftInfo()
{
Shift_Name = "Shift Name Example",
ShiftAvgTarget = 12345
};
ViewBag.TblShiftInfo = tblShiftInfo;
return View();
}
In the view, you can use the ViewBag:
<p>#ViewBag.TblShiftInfo.Shift_Name</p>
Hope it helps!
I am a beginner to ASP.NET MVC technology.
In my View page, I have a WebGrid that is bind to data that is passed from Controller. I also want to populate a dropdown list with the list of Tables in the database. I retrieve the tables List from a helper method. I am trying to send the List to the ViewBag and want to populate the dropdown; but can't get it. Some syntax error is only coming or the List is not accessible.
My Controller class :
[Authorize]
public ActionResult Index(int page = 1, string sort = "FirstName", string sortdir = "asc", string search = "")
{
int pageSize = 10;
int totalRecord = 0;
if (page < 1)
page = 1;
int skip = (page * pageSize) - pageSize;
var data = GetUsers(search, sort, sortdir, skip, pageSize, out totalRecord);
// Get Tables List
ViewBag.TableList = DataFiller.GetTableNames();
ViewBag.TotalRows = totalRecord;
return View(data);
}
View file :
#model List<DataStudio.Models.User>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_MemberLayout.cshtml";
<!-- data is used for grid -->
var grid = new WebGrid(canPage: true, rowsPerPage: 10);
grid.Bind(source: Model, rowCount: ViewBag.TotalRows, autoSortAndPage: false);
}
<!-- ERROR LINE -->
#Html.DropDownList("tableName", #ViewBag.TableList, "Select Table")
ERROR
Error CS1973 'HtmlHelper<List<User>>' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax. 1_Views_Member_Index.cshtml Index.cshtml 82 Active
The User model doesn't contain any List nor any DropDownList. The drop down is a totally separate combo box, that I want to fill with a List items; it just contains the list of table names from the database.
I am not able to get how do I bind or populate the drop down list with the SelectLiteItem items. I googled a lot, but could not get any example with this scenario. I don't wish to add my List with my model. And, I want to populate the Tables list drop down only once.
Can anyone please help me and guide me how do I achieve the goal. Any help is highly appreciated.
Thanks
Tom
UPDATE:
The DataFilter.GetTableNames() method
public static List<SelectListItem> GetTableNames()
{
List<SelectListItem> tablesList = new List<SelectListItem>();
string sql = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'";
string conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DMSDbConnectionString"].ToString();
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand com = new SqlCommand(sql, con)) {
con.Open();
using(SqlDataReader sdr = com.ExecuteReader() )
{
while (sdr.Read())
{
tablesList.Add(new SelectListItem
{
Text = sdr["TABLE_NAME"].ToString(),
Value = sdr["TABLE_NAME"].ToString()
});
}
}
/*
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds);
DataTable dt = ds.Tables[0];
tablesList = (from DataRow dr in dt.Rows
select new TablesInfo()
{
TableCatalog = dr["TABLE_CATALOG"].ToString(),
TableName = dr["TABLE_NAME"].ToString(),
TableSchema = dr["TABLE_SCHEMA"].ToString(),
TableType = dr["TABLE_TYPE"].ToString(),
}).ToList();
*/
con.Close();
}
}
return tablesList;
}
I had created a class also TablesInfo to populate data in it and use strong typed object. But, as couldn't find a way to populate it, so used SelectListItem.
And as it contains only list of tables, so I don't wish it to be populated on every refresh of the page.
You can't use ViewBag dynamic object which contains List<User> directly to a DropDownList HTML helper, you need to cast it into SelectList instead:
#Html.DropDownList("tableName", (SelectList)ViewBag.TableList, "Select Table")
Additionally, DataFiller.GetTableNames() method call should returns SelectList instance:
class DataFiller
{
public SelectList GetTableNames()
{
// set select list items here
}
}
NB: I strongly prefer using a strongly typed view model instead using ViewBag or ViewData to pass a list to HTML helper like this:
#Html.DropDownListFor(model => model.tableName, Model.TableList as SelectList, "Select Table")
Related issue:
MVC3 DropDownList + ViewBag issue
As Tetsuya stated, you should be using a strongly typed view model.
You can structure your model like this:
public class MyUserCollection
{
public List<MyUser> Users { get; set; }
public SelectList TableList { get; set; }
public int TotalRows { get; set; }
public MyUserCollection(string search, string sort, string sortdir, int skip, int pageSize)
{
TableList = DataFiller.GetTableNames();
Users = GetUsers(search, sort, sortdir, skip, pageSize, out totalRecord);
}
}
Then to create your drop down:
#Html.DropDownListFor(model => model.tableName, Model.TableList as SelectList, "Select Table")
Other wise you need to cast your object:
#Html.DropDownList("tableName", (SelectList)ViewBag.TableList, "Select Table")
Please use below code i hope that will help your query.
ViewBag.TableList = DataFiller.GetTableNames();
#Html.DropDownList("ID", new SelectList(ViewBag.TableList, "ID", "Name"));
You can actually do it like below too:
#Html.DropDownListFor(m => m.tableName, (IEnumerable<SelectListItem>)ViewBag.TableList ,"select table")
Hey all I am new to Razor MVC and wanted to make a select box that has the past 10 years listed inside it (2016, 2015, 2014, etc....).
This is my current Controllers code:
public ActionResult loadPast10Years()
{
List<int> last10Years = new List<int>();
int currentYear = DateTime.Now.Year;
for (int i = currentYear - 10; i < currentYear; i++)
{
last10Years.Add(i);
}
ViewBag["last10Years"] = last10Years;
return View();
}
And my Razor code:
#Html.DropDownList("last10Years", (SelectList)ViewBag["last10Years"], "--Select One--")
But I have an error when loading the page that says:
InvalidOperationException: There is no ViewData item of type 'IEnumerable' that has the key 'last10Years'.
So... What am I missing?
This is how I would do it in the view
#Html.DropDownList("Last Ten Years", (IEnumerable<SelectListItem>)ViewBag.LastTenYears, "Select A Year")
and in your Action
List<int> last10Years = new List<int>();
int currentYear = DateTime.Now.Year;
for (int i = currentYear - 10; i < currentYear; i++)
{
last10Years.Add(i);
}
ViewBag.LastTenYears = new SelectList(last10Years);
You can see a demo here
Following from your comment please find below my updated answer.
I would first create a Model class which we will be using in our view. In this model class you can have your appropriate properties. For now we're only going to be using SelectlistItem
so our class will look like
public class ViewModel
{
public IEnumerable<SelectListItem> LastTenYears { get; set; }
}
Then in our controller we can create a method which will provide us the information for our drop down.
public IEnumerable<SelectListItem> GetLastTenYears()
{
List<SelectListItem> ddl = new List<SelectListItem>();
int currentYear = DateTime.Now.Year;
for (int i = currentYear - 10; i < currentYear; i++)
{
ddl.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() });
}
IEnumerable<SelectListItem> lastTenYears = ddl;
return lastTenYears;
}
Now we want to pass this data to the view. For argument sake I will use Index as a view but you can pass it to whatever view you like. So we will change our Index action to
public ActionResult Index()
{
ViewModel viewModel = new ViewModel();
viewModel.LastTenYears = GetLastTenYears(); //get the drop down list
return View(viewModel); //we're passing our Model to the view
}
Finally, we want to make sure our view knows which Model to use so we will do the following the beging of the Index.cshtml file
#model YourNameSpace.ViewModel
and our DropDownList helper method will now change to point to the property in our Model class as
#Html.DropDownList("Last Ten Years", Model.LastTenYears, "Please select a year")
There are few issue in your code right now.
Don't name the ViewBag key same as the DropDownList name, they don't
work well together, you can change the ViewBag Key name to something like last10YearsOptionsinstead oflast10Years`, so that it is different than control name.
You have not create SelectList in controller before adding to ViewBag, but you are casting it to SelectList in View.
In ViewBag values are stored like ViewBag.SomeKey= "SomeValue", but you are doing it wrong way.
After Fixing the above problems your code will look like :
ViewBag.last10YearsOptions = last10Years.Select(x => new SelectListItem()
{
Text = x.ToString(),
Value = x.ToString()
}
);
and then in View:
#Html.DropDownList("last10Years",
"--Select One--",
ViewBag.last10YearsOptions as IEnumerable<SelectListItem>,
null )
ViewBag is not a dictionary with key value pairs.
also DropDownList works with ICollection ithink
so this code works form
#Html.DropDownList("last10Years", new SelectList(ViewBag.last10YearsOptions), "Select one from here")
Controller is here;
public ActionResult loadPast10Years()
{
List<int> last10Years = new List<int>();
int currentYear = DateTime.Now.Year;
for (int i = currentYear - 10; i < currentYear; i++)
{
last10Years.Add(i);
}
ViewBag.last10Years = new SelectList(last10Years);
return View();
}
And View
#Html.DropDownList("last10Years", "--Select One--")