Show list-items in view - c#

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>
}
}

Related

Passing data from SQL to MVC Array System.String[] Error

I'm passing a Stored Procedure into my Controller, which I then want to send to my View and log each entry of the Stored Procedure into a dropdown menu. My problem is that when I pass the data over to the dropdown menu, all I get is System.String[] instead of the actual value.
Controller:
public ActionResult Dropdown()
{
ViewData["ids"] = db.uspGetAllEventIds().ToArray();
return View();
}
View:
#model IEnumerable<Heatmap.Models.Event>
...
<body>
<div>
<select name="EventId">
#for (var i = 0; i < 6; i++)
{
<option>#ViewData["ids"]</option>
}
</select>
</div>
</body>
Right now I only have a simple for loop set to 6, but I want to iterate through my entire ids array (which should be filled with the values from db.uspGetAllEventIds() and enter them into my dropdown menu. How should I set my loop up to do this?
To use a string array inside ViewData object, you need to cast ViewData into string[] with as operator (or simply a direct casting if you're sure not throwing exception) and later iterate the contents as shown in code below:
#model IEnumerable<Heatmap.Models.Event>
...
<body>
<div>
<select name="EventId">
#{
// a simple (string[])ViewData["ids"] also work here
var ids = ViewData["ids"] as string[];
for (var i = 0; i < 6; i++)
{
<option>#ids[i]</option>
}
}
</select>
</div>
</body>
Working example: .NET Fiddle Demo
NB: You can't access array elements using ViewData["ids"][i] inside for loop because ViewData is a dynamic dictionary which has object type, not object[].
Tip: If you want to iterate through entire ids array, use ids.Length as upper limit value in for loop after casting ViewData.
Reference:
ASP.NET MVC - How to pass an Array to the view?
How to pass an array from Controller to View?

GridMVC Grid Throws Cast exception?

I'm trying to create a simple Grid using GridMVC
Here is my Controller code.
public ActionResult Index()
{
var approvals = new List<Host_Apps>();
approvals = db.Host_Apps.ToList();
return View(approvals);
}
HTML:
#{
Layout = null;
}
#model List<TrackMiPD.Models.Host_Apps>
#using GridMvc.Html
<h2>Index</h2>
<body>
<div>
#Html.Grid(Model,"Index").Columns(columns =>
{
columns.Add(data => data.ApprovalId).Titled("First Name").SetWidth(110);
columns.Add(data => data.Name).Titled("Last Name").SetWidth(110);
columns.Add(data => data.State).Titled("Age").Sortable(true);
columns.Add(data => data.City).Titled("Birth Date").Sortable(true);
}).WithPaging(20)
</div>
</body>
I tried passing IEnumerable instead of List. I vaguely remember long agao I was working with GridMVC that after setting layout= Null it started working So ive put Layout as Null
Here is the error I get
The model item passed into the dictionary is of type
'GridMvc.Html.HtmlGrid1[TrackMiPD.Models.Host_Apps]', but this
dictionary requires a model item of type
'System.Collections.Generic.List1[TrackMiPD.Models.Host_Apps]'.
Try creating a wrapper class for List of Host_Apps, That would have a list of Host_Apps. Then pass it as model to your view.
During access in view access it as:
#Html.Grid(Model.Host_Apps)
The same problem I had but was able to walk away with this.

Put ViewBag Controller Value on View

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)

Binding DropDownListFor In foreach , ASP.NET MVC

Here is my code :
ViewModel
public class FooViewModel{
public Guid BarId { set;get }
}
View :
#model IEnumerable<FooViewModel>
#foreach (var c in Model)
{
<div>
#Html.DropDownListFor(o => c.BarId , (List<SelectListItem>)ViewBag.BarCollection)
</div>
}
the problem is DropDownListFor create the options completely but binding doesn't work.
You cannot use a foreach loop to generate controls for items in a collection. If you inspect the html you will see that you have duplicate name attributes without indexers (and also duplicate id attributes which is invalid html). You need a for loop of a custom EditorTemplate for FooViewModel. Using a for loop (your model must implement IList<T>)
#model IList<FooViewModel>
for (int i = 0; i < Model.Count; i++)
{
#Html.DropDownListFor(m => m[i].BarId, ....)
}
Note the html will now be
<select name="[0].BarId" ..>
<select name="[1].BarId" ..>
etc.

How do I Bind a Collection (IEnumerable) of a custom type?

I have the following Action to display a form with 3 items :
[HttpGet]
public ActionResult ReferAFriend()
{
List<ReferAFriendModel> friends = new List<ReferAFriendModel>();
ReferAFriendModel f1 = new ReferAFriendModel();
ReferAFriendModel f2 = new ReferAFriendModel();
ReferAFriendModel f3 = new ReferAFriendModel();
friends.Add(f1);
friends.Add(f2);
friends.Add(f3);
return View(friends);
}
and then a Post action
[HttpPost]
public ActionResult ReferAFriend(IEnumerable<ReferAFriendModel> friends)
{
if(ModelState.IsValid){
EDIT
My View looks like this:
#model IEnumerable<Models.ReferAFriendModel>
#for(int i=0;i<Model.Count();i++)
{
#Html.Partial("_ReferAFriend", Model.ElementAt(i));
}
The partial looks like this:
#model Models.ReferAFriendModel
<p>
#Html.LabelFor(i => i.FullName) #Html.TextBoxFor(i => i.FullName)<br />
#Html.LabelFor(i => i.EmailAddress) #Html.TextBoxFor(i => i.EmailAddress)
#Html.HiddenFor(i=>i.Id)
</p>
When I post, I can see the fields are posted in the Request.Form object e.g Request.Form["FullName"] will show: "David Beckham","Thierry Henry". "Chicharito Fergurson" which are the values I entered in the form. But, the in the Post action,the value for 'friends' is always null. The ReferAFriendModel has three public properties Id, EmailAddress and FullName.
What am I doing wrong?
You may take a look at the following blog post about the wire format for arrays and dictionaries. Personally I always use editor templates in my views which take care of generating proper names of the input fields so that the default model binder is able to bind the values correctly.
#model IEnumerable<ReferAFriendModel>
#using (Html.BEginForm())
{
#Html.EditorForModel()
<input type="submit" value="OK" />
}
and in the corresponding editor template (~/Views/Shared/EditorTemplates/ReferAFriendModel.cshtml):
#model ReferAFriendModel
#Html.EditorFor(x => x.Prop1)
#Html.EditorFor(x => x.Prop2)
...

Categories