GridMVC Grid Throws Cast exception? - c#

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.

Related

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>

LIST<VIEWMODEL> in view object is returning null in controller mvc.net

I have a list of class object and which is bind with view like this
#model List<Rep.Models.ContactReportSettingViewModel>
var accountArr = Model.Select(x => new { x.AccountId, x.CarrierId, x.AccountNumber, x.CarrierName, x.ClientId, x.ContactId }).Distinct();
I have a loop here on var object
#foreach (var accountRow in accountArr)
{
#Html.LabelFor(x => accountRow.AccountNumber, accountRow.AccountNumber, new { #id = accountRow.AccountId })
but when I click on save it is returning null or values or not set with the class properties I am accessing this in controller like this:
public RESULT method(List<ContactReportSettingViewModel> model)
{
model is null here
// return View(model);
}
But in model I am getting null. What I am doing wrong?
When I use this
public RESULT method(ContactReportSettingViewModel model)
{
// return View(model);
}
Then in model object I can see all the properties but values does not set to those properties
You cannot use a foreach loop to generate form controls for a collection because your generating duplicate name attributes that have no relationship to your model (and duplicate id attributes which is invalid html). You can use either a for loop in the view, or use an EditorTemplate for your model.
Note you need to remove your Linq .Select() code and do the filtering in the controllers GET method.
Using a for loop in the main view (note the model must be IList<T>)
#model List<Rep.Models.ContactReportSettingViewModel>
#using (Html.BeginForm())
{
#for (int i = 0; i < Model.Count; i++)
{
#Html.LabelFor(m => m[i].AccountNumber)
#Html.TextBoxFor(m => m[i].AccountNumber)
#Html.ValidationMessageFor(m => m[i].AccountNumber)
.....
}
<input type="submit" .../>
}
Using an EditorTemplate. Create a partial view in /Views/Shared/EditorTemplates/ContactReportSettingViewModel.cshtml (note the name of the file must match the model class name)
#model Rep.Models.ContactReportSettingViewModel
#Html.LabelFor(m => m.AccountNumber)
#Html.TextBoxFor(m => m.AccountNumber)
#Html.ValidationMessageFor(m => m.AccountNumber)
.....
and then in the main view (note the model can be IEnumerable<T>)
#model IEnumerable<Rep.Models.ContactReportSettingViewModel>
#using (Html.BeginForm())
{
#Html.EditorFor(m => m)
<input type="submit" .../>
}
In both cases the generated html will include the correct name attributes with indexers which will be bound to your model in the POST method
<input type="text" name="[0].AccountNumber" .. />
<input type="text" name="[1].AccountNumber" .. />
Follow the following checklist
1) Make sure you added thing binding statement on top of your view
#model List<ClassName>
2) Then check your is being submitted to the function your mentioned in question and also check the parameter type is same as you mentioned while binding the page.
if you are using html table type structure to display list items then you also need to bind your list with each row. like
for Cell[0][0] bind yourList[0].EmployeeId, Cell[0][1] bind yourList[0].EmployeeName and so on for all the column and then rows by using loop.

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

IEnumerable property is null after submit

I am new to MVC and have some difficulties understanding this.
To make it simple, I have a "Person" object and this object has an IEnumerable property called "EmailaddressList".
I have generated an edit page through Visual Studio 2012. The main objects properties, are generated on the edit page with textboxes like Name and LastName.
However the list of e-mail addresses in the IEnumerable list of sub-objects are not generated automatically in my view.
This is OK, I have written that code by hand using a tab for each type of e-mailaddress.
So far so good.
Problem:
When I recieve the model (person object) in my HTTP-Post method, the EmailAddressList is null.
Why is it like this, It was not null when I sent it to the view.
I the tab where the e-mailadresses are listed is in a partial view.
Can anyone give me some tips, is it something I'm missing here?*
View-Code
<div id="tabs">
<ul>
#foreach (var item in Model.EmailAddressList)
{
<li>#Html.Label(item.AddressType)</li>
}
</ul>
#foreach (var item in Model.EmailAddressList)
{
<div id="#item.AddressType">
<p>
#Html.TextBoxFor(s => item.EmailAddress, new { #class = "input-xxlarge" })
</p>
</div>
}
</div>
Controller (recieving method)
Here person.EmailAddressList is null
[HttpPost]
public ActionResult Create(Person person)
{
if (ModelState.IsValid)
{
personRepository.InsertOrUpdate(person);
personRepository.Save();
return RedirectToAction("Index");
}
else
{
return View();
}
}
That's because in order to correctly index your fields (so model binder can do it's work), you have to use a for loop.
First, change your IEnumerable to be a List (so we can use an indexor in the view).
Then change your foreach to be the following for loop:
#for (int i = 0; i < Model.EmailAddressList.Count; i++)
{
<div id="#Model.EmailAddressList[i].AddressType">
<p>
#Html.TextBoxFor(m => m.EmailAddressList[i].EmailAddress, new { #class = "input-xxlarge" })
</p>
</div>
}
Based on your update, the reason this doesn't work is because the default model binder only relies on order for a collection of simple data. When it comes to complex type you need to provide the relevant index per item otherwise it doesn't know which item property your referring to e.g.
#for (int i = 0; i < Model.EmailAddressList.Count; i++) {
Html.TextBoxFor(m => m.EmailAddressList[i].EmailAddress) %>
}
See Phil Haack's article on model binding to a list.
It's due to your elements not being ID'd the correct thing for MVC to pick them up on the post back, what you need is:
#Html.EditorFor(model => model.EmailAddressList);
Then, please refer to my post located here on how to make this look to how you want it to.

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