is it possible to add a texbox by controller to a View?
I have a dynamic number of textboxes and need a way to add this by the Controller to the View. Is this Possible?
Do Something like this. Just a quick written code. Might be syntax errors.
DynamicTextBoxCreation.cs
public class DynamicTextBoxCreation
{
public List<string> textBoxList;
public ActionResult DynamicTextBox()
{
/* Fill your dynamic list here from DB or from any other logic */
return textBoxList;
}
}
DynamicTextBox.cshtml
#model DynamicTextBoxCreation;
#code{
var i = 1;
}
foreach(var tbItem in textBoxList)
{
#Html.TextBox(' + tbItem + i + ', "", new {#class = "css-class", #onclick = "alert('demo');"});
i += 1;
}
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")
I want to pass the values from database list to the ViewModels' local variable in controller. I wanted to use GetValue method to do so but it doesn't exist in this context and I have no idea why.
public ActionResult Index()
{
MySQL msql = new MySQL();
List<string> results = msql.SelectList("Select * from table");
var model = new List<MyViewModels>(results.Count);
for (int i = 0; i < results.Count; i++)
{
model.Add(new MyViewModels() {
//this is want I want to do but GetValue method doesn't exist
bID = results[i].GetValue("bID");
status = results[i].GetValue("status")
});
}
return View(model);
}
Because results is a List<string> you are effectively trying to call "".GetValue("bID") which is not possible. Strings have no GetValue function.
This also does not make any sense
List<string> results = msql.SelectList("Select * from table");
This will ONLY work if the table only has one column.
I am trying, to no avail to display a dropdown list of all units a user doesnt already have. So i have List A with all Units and List B with all Units the user has. What i want is List C which is basically List A with List B removed from it. I have so far managed to filter out the data but i cant seem to display it in my View. All i get is a blank dropdown list. Can anyone see where im going wrong??
public ActionResult AddUnit(String usrCode)
{
var units = unitsClient.GetAllunits();
var allunitsCode = (from s in units select s.unitCode).ToList();
var thisUnitCode = (from s in db.Units
where s.UsrCode == usrCode
select s.UnitCode).ToList();
var notGot = allunitsCode.Except(thisUnitCode);
List<unitsummaryDTO> list = UnitList(units, notGot);
ViewBag.unitCode = new SelectList(list, "unitCode", "unitTitle");
var model = new UserUnit { UsrCode = usrCode };
return View("AddUnit", model);
}
private List<unitsummaryDTO> UnitList(unitsService.unitsDTO[] units, IEnumerable<string> notGot)
{
var allunits = unitsClient.GetAllunits();
var allunitsCode = (from s in allunits select s.unitCode).ToList();
IEnumerable<String> list1 = allunitsCode;
IEnumerable<String> list2 = notGot;
var listFinal = list1.Union(list2).toList;
return listFinal.Select(x => new unitsummaryDTO(){unitCode = x}).ToList();
}
This is my View model. But all i get is a blank drop down?? Can anyone help me out.
#model Projv1.UserUnit
#Html.HiddenFor(model => model.unitCode)
#Html.DropDownList("UnitCode")
It would be blank because #Html.DropDownList("UnitCode") doesn't have a source. If you look at MSDN for Html.DropDownList, the one your most likely trying to use is DropDownList(String, IEnumerable<SelectListItem>).
Your putting your select list into the ViewBag as unitCode so try:
#Html.DropDownList("Unit Code", ViewBag.unitCode);
A much easier way of handling this is to extend UserUnit as a ViewModel (or create something) to have the items needed by the SelectList on it and let MVC do the heavy lifting in the binding.
public class UserUnit
{
// ... other properties
IEnumerable<unitsummaryDTO> UnitCodes { get; set; }
public string MyUnitCode { get; set; }
}
Then
#Html.DropDownListFor(n => n.MyUnitCode,
new SelectList(Model.UnitCodes, "unitCode", "unitTitle"))
I am confused on an issue with the DropDownListFor helper.
I am trying to assign a list of values to the drop down as follows:
Model
public Int32 TestID {get;set;}
public List<Int32> ListOfID {get;set;}
public IEnumerable<SelectListItem> TimeDD {get;set;}
Controller
public ActionResult Manage(int id){
MyModel model = new MyModel();
model.TimeDD = DropDownManager.TimeDD;
model.TestID = 12;
model.ListOfID = new List<Int32>{ 1,2,3,4,5,6,7};
return View(model);
}
In the view I have the following:
#for(int i = 0; i< ListoFID.Count; i++){
<div>#Html.DropDownListFor(m=> m.TestID, Model.TimeDD)</div>
<div>#Html.DropDownListFor(m=> m.ListoFID[i], Model.TimeDD)</div>
}
The problem I am having is that the TestID drop down is working correctly however the ListoFID[i] is not selecting the values from the drop down. The TimeDD is a list of times as follows:
/// <summary>
/// The Time dropdown
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public static IEnumerable<SelectListItem> TimeDD()
{
// new ctl
TimeControl ctl = new TimeControl();
// get drop down
IEnumerable<SelectListItem> result = ctl.Select().Select(m => new SelectListItem { Text = m.Time1, Value = m.TimeID.ToString() }).ToList();
// clean up
ctl.Dispose();
return result;
}
Where Time1 is '09:30' and TimeID is 1 - 48. I cannot figure out how this is happening!! As soon as I reference an object it fails to select the drop down at the correct point.
Edit
Also I have a property in my model called OpeningTimes - this is the list of opening times saved against a company as below:
ComapnyID DayID StartTime EndTime
1 1 19 32 -- e.g. Monday 09:00 - 17:30
When I loop through the Opening times:
#for(int i=0; i< Model.OpeningTimes.Count; i++)
{
<tr>
<td>
#Html.DropDownListFor(m => m.OpeningTimes[i].StartTime, Model.TimeDD)
</td>
<td>
#Html.DropDownListFor(m => m.OpeningTimes[i].EndTime, Model.TimeDD)
</td>
</tr>
}
The drop downs are still not being selected. I can confirm the StartTime and EndTime do have values and are property int
DropDownListFor requires a property to map to, not a value. So
#Html.DropDownListFor(m=> m.ListoFID[i], Model.TimeDD) /* the [i] kills it */
will not work.
instead of doing a list of int build it like the other
List<SelectListItem> ls = new List<SelectListItem>();
foreach(var temp in Model.ListOfId){
ls.Add(new SelectListItem() { Text = temp, Value = temp});
}