Put ViewBag Controller Value on View - c#

I'm trying to pass a ViewBag data from my controller to my View, if i put the Viewbag on a Html.DropDownList I get the correct values but if I use <input value="#ViewBag.Group" /> I only get "System.Web.Mvc.SelectList"
Why am I not getting the value of my viewbag?
This is my controller ViewBag:
public ActionResult Index(string Selected)
{
List<string> listadesumas = new List<string>();
var db = new PosContext();
foreach (var item in db.Pos)
{
listadesumas.Add(item.ToString());
}
var grupos = new SelectList(listadesumas.ToList());
ViewBag.Group = grupos;
return View("~/Views/HomePos/Index.cshtml",db.Pos.ToList());
}
and my Input From View:
<input value="#ViewBag.Group" />
what am i doing wrong?

#{
var group = (SelectList)ViewBag.Group
}
<select>
#foreach(var item in group)
{
<option value='#item'>#item</option>
}
</select>

Viewbag.Group contains a list of values. An input tag can only take exactly one value.

i manage to get another aproach using a boxlist, heres the code in case someone needs it:
#Html.ListBox("Group", (IEnumerable<SelectListItem>)ViewBag.Group)

Related

MVC 4 C# How to Retrieve Configuration Values in Controller to Bind Dropdown in View

I am trying to fill a drop down in my index view with the values I have listed in web.config.
<add key="DropdownValues" value="Value1, Value2, Value3" />
I want to grab Value1, Value2, and Value3 from the config and bring it into a dropdown list with a friendly display name for each value.
Value from the list will be used when submit is hit and a server is queried and returns results into a table.
I am not sure how to code the controller part of this to grab the values and send over to the index page (using viewbag?) Other examples involved creating a ViewModel but I want to be able to add to the values in the future without having to re-compile the app that's why I want it in the config.
Please show me an example as I am still new to MVC.
I assume in the view I would do something like:
#Html.DropDownListFor(model => model.YourModelProperty,
(IEnumerable)ViewBag.DropDownList, "---Select a value---")
Step 1 (In controller ActionResult Method): read the values from the config:
using System.Configuration;
string configvalue1 = ConfigurationManager.AppSettings["DropdownValues"];
Step 2 (In controller ActionResult Method): Parse them to an array by the comma and trim any space in front or behind the parsed text:
string[] values = configvalue1.Split(',').Select(sValue => sValue.Trim()).ToArray();
Step 3 (In controller ActionResult Method): Declare a selectlistItem List, Iterate through array to populate:
List<SelectListItem> dropDowns = new List<SelectListItem>();
for (int i = 0; i < values.Length; i++)
{
dropDowns.Add(new SelectListItem { Text = values[i], Value = values[i] });
}
Step 4 (In controller ActionResult Method): Assign them in your ViewBag:
ViewBag.DropdownVals = dropDowns;
Step 5: (In your view) set a dropdown list that is bound to your viewbag item. You need to explicitly cast it to a IEnumerable SelectListItem object here or the razor engine will get angry!!!
#Html.DropDownList("YourElementName", (IEnumerable<SelectListItem>)ViewBag.DropdownVals, "--Choose Your Value--")
Full Controller:
public ActionResult Index()
{
string[] values = (ConfigurationManager.AppSettings["DropdownValues"]).Split(',').Select(sValue => sValue.Trim()).ToArray();
List<SelectListItem> dropDowns = new List<SelectListItem>();
for (int i = 0; i < values.Length; i++)
{
dropDowns.Add(new SelectListItem { Text = values[i], Value = values[i] });
}
ViewBag.DropdownVals = dropDowns;
return View();
}
Full View:
#{
ViewBag.Title = "Index";
}
#Html.DropDownList("YourElementName", (IEnumerable<SelectListItem>)ViewBag.DropdownVals, "--Choose Your Value--")
Try doing something like this
Controller:
public ActionResult Index()
{
var GetWebConfigValue1 = System.Configuration.ConfigurationManager.AppSettings["WebConfigValue1"].ToString();
ViewBag.WebConfigValue1 = GetWebConfigValue1;
// Repeat the lines of code above to get more values
return View();
}
View:
<select>
<option selected="true" disabled="disabled">Choose a Value</option>
<option value="#ViewBag.WebConfigValue1">#ViewBag.WebConfigValue1</option>
<option value="#ViewBag.WebConfigValue2">#ViewBag.WebConfigValue2</option>
<option value="#ViewBag.WebConfigValue3">#ViewBag.WebConfigValue3</option>
</select>

The model item passed into the dictionary is of type 'AMSPractice.Models.AddTable'

I am very new to asp.net and i am stuck on that code i cant resolve this error
"The model item passed into the dictionary is of type 'AMSPractice.Models.AddTable', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[AMSPractice.Models.AddTable]'."
I want to show only one value for example in my table there is more than one values name "first" so i want to show only one time "first" so when we write
FirstOrDefault then give error and when we write Where then error is not shown
but i want back only one value where return more then one values.
Here is my code
Controller
public ActionResult Login(string Name,string TeacherID)
{
AdmissionDBEntities obj = new AdmissionDBEntities();
AddTable t = new AddTable();
var v = obj.AddTables.FirstOrDefault(a => a.Teacher.Equals(Name) && a.Teacher_Id.Equals(TeacherID));
if (v != null)
{
**var var = obj.AddTables.FirstOrDefault(b => b.Teacher==Name);**
return View(var);
}
return RedirectToAction("/Home/Index");
and my View is:
#model IEnumerable<AMSPractice.Models.AddTable>
<h3>Classes Assigned</h3>
<br /><br />
<ul>
#foreach (var a in Model)
{
<li>
#Html.ActionLink(a.Class,"Sections","Attendance", new { nid = a.Foreign_Id }, null)
</li>
}
</ul>
Your issue is from the way you have strongly typed your view. From your controller, when you return return View(var); you are passing a single object to your view, yet your view is strongly typed to expect an IEnumerable of the AddTable object.
You either need to return an IEnumerable from your controller, or change your view to expect only a single object.
Try the following to change your view to expect only a single object.
In your view change your strongly typed #model from what you have to #model AMSPractice.Models.AddTable
At that point, you wouldn't need the foreach and you would just have the following.
<li>
#Html.ActionLink(a.Class,"Sections","Attendance", new { nid = Model.Foreign_Id}, null)
</li>

Select Tag Helper binding with an array or list

How can my following controller Action Method bind a list of integers to a Select Tag Helper in my ASP.NET Core project without using ModelView? Or, without ModelView this cannot be done?
Action Method:
public IActionResult ListofDays()
{
IEnumerable<int> DaysList = Enumerable.Range(1, 7).ToList();
return View(DaysList);
}
Select Tag:
<select asp-for="???" asp-items="???"></select>
You can convert the int array to a list of SelectListItem which can be used as your asp-items property value of select tag helper.
public IActionResult Index()
{
var daysList =Enumerable.Range(1, 7)
.Select(g => new SelectListItem {Value = g.ToString(), Text =g.ToString()}).ToList();
return View(daysList);
}
Now in the view which is strongly typed to a list of SelectListItem,
#model List<SelectListItem>
<form asp-action="Index" asp-controller="Home">
<select name="MyDay" asp-items="Model"></select>
<input type="submit"/>
</form>
When you submit the form, the selected day will be in the MyDay form element. You may use a parameter with the same name in your HttpPost action method to receive it.
For your reference :
Select Tag Helper in MVC 6

Show list-items in view

I'm pretty new to c# and MVC
I created a FormController.cs with a method like:
public ActionResult Showlist()
{
List<int> list = new List<int>();
list.Add(54);
list.Add(524);
list.Add(23);
list.Add(43);
return View(list);
}
Then I create a view from that method. In my div-tags I put the text like:
<body>
<div>
#Model.ToString();
</div>
</body>
The result is a view with the text System.Collections.Generic.List`1[System.Int32]
My question: What's a good (or best) way to show the values that I added in the list?
Also you need to declare the Model as a list in the cshtml:
#model IEnumerable<int>
#{
foreach (var anInt in Model)
{
<text>#anInt</text>
}
}

Edit View with child entity selection listbox and HTTPPost difficulties

I have a Search Edit view which is strongly typed to my Search model class seen below (simplified).
I want to display the custodians that are attributed to the Search being edited in a listbox showing all Custodians, with the current ones selected.
My controller's Get Edit action is thus:
public ActionResult Edit(int id, int searchListId = 0)
{
if (searchListId != 0)
{
Session["CurrentSearchListID"] = searchListId;
}
ProjectContext mydb = db;
Search search = Search.Find(mydb, id);
IEnumerable<SelectListItem> selectedItems =
from c in Custodian.List(mydb)
select new SelectListItem
{
Selected = (search.Custodians.Contains(c)),
Text = c.CustodianName,
Value = c.ToString()
};
ViewBag.Custodians = selectedItems;
return View(search);
}
And my Views listbox is thus:
#{
//List<Kiersted.Keps.BusinessObjects.Custodian> Custodians = ViewBag.Custodians;
IEnumerable<SelectListItem> SelectedItems = ViewBag.Custodians;
}
#Html.ListBox("Custodians", SelectedItems);
This produces a listbox with the Custodians depicted, but none are selected (I have confirmed that several of the SelectListItems accurately describe the custodian as selected. I have tried using ListBoxFor and it produces the same thing when populated with a MultiSelectList.
Finally I decided to just force it to do what I want, but this does not return selected Custodians on Submit.
<select id="Custodians" multiple="multiple" name="Custodians">
#foreach (Kiersted.Keps.BusinessObjects.Custodian cust in Custodians)
{
if (Model.Custodians.Contains(cust))
{
<option value="#cust.CustodianID" selected="selected">#cust.CustodianName</option>
}
else
{
<option value="#cust.CustodianID" >#cust.CustodianName</option>
}
}
</select>
Anyone know how you are supposed to do this?
Edits:
ListBoxFor example
OK so after fiddling around with it for a while longer, I have now gotten Custodians selected in the listbox that correspond to the Search Custodians. Below is the view code:
<div class="editor-field">
#Html.ListBoxFor(model => model.Custodians, allCustodians.Select(cust => new SelectListItem {
Text = cust.CustodianName,
Value = cust.CustodianID.ToString(),
Selected = true}),
new { Multiple = "multiple" })
</div>
If I select several more custodians, how do I get them (or their corresponding values rather) back to the control upon submit?
Seeing that after your edit the problem boils down to multiple select model binding, perhaps you will find these useful?
How does a multiple select list work with model binding in ASP.NET MVC?
http://ittecture.wordpress.com/2009/04/30/tip-of-the-day-198-asp-net-mvc-listbox-controls/

Categories