List not converting to IEnumerable - c#

Below is the error i getting :
The model item passed into the dictionary is of type 'System.Collections.Generic.List[StoredProcedureEF_MVC.tbl_users]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable[StoredProcedureEF_MVC.Models.User]'.
I have tried a lot but don't know where i was doing wrong, no luck from last two days. I am learning MVC, so sorry if you got some stupid mistake.
My Model :
namespace StoredProcedureEF_MVC.Models
{
[Table("tbl_users")]
public class User
{
[Key]
public int UserId { get; set; }
[Required]
public string Username {get;set;}
[Required]
public string Email { get; set; }
}
}
VIEW:
#model IEnumerable<StoredProcedureEF_MVC.Models.User>
#{
ViewBag.Title = "Delete";
}
#{
var grid = new WebGrid(source: Model);
}
#grid.GetHtml(
columns: grid.Columns(
grid.Column("UserID"),
grid.Column("Username"),
grid.Column("Email"),
grid.Column(
format: (item) => Html.ActionLink("Delete", "DeleteUser", new {id=item.UserID })
)
)
)
CONTROLLER ACTION:
[HttpGet]
public ActionResult Delete()
{
SPEFMVCEntities conn = new SPEFMVCEntities();
var result = (from p in conn.tbl_users select p).ToList();
return View(result);
}

try
var result = conn.tbl_users.Select(c => new StoredProcedureEF_MVC.Models.User
{
UserId = c.UserId,
UserName = c.UserName,
Email = c.Email
}).ToList();
return View(result);

Try to change your controller method to this:
[HttpGet]
public ActionResult Delete()
{
SPEFMVCEntities conn = new SPEFMVCEntities();
var result = (from p in conn.tbl_users select p as StoredProcedureEF_MVC.Models.User).ToList();
return View(result);
}

Related

Searching a record by name and id

I'm working with ASP.Net MVC with SQL server management studio.
Now how would I get a record by a given name and/or id?
Currently, I only find a record using the id which just works fine, but when searching a record by name, it won't find the correct record.
My current code looks something like this:
//Student.cs
public partial class Student
{
public int No { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public Nullable<decimal> mobileno { get; set; }
public string Image { get; set; }
}
//Index.cshtml
#using (Html.BeginForm("search", "CrudManually", FormMethod.Post))
{
#Html.TextBox("id")<br/>
#Html.TextBox("searchString")<br/>
<input type="submit" value="Search"/>
}
//CrudManuallyController.cs
public class CrudManuallyController : Controller
{
public ActionResult Index()
{
return View(db.manages.ToList());
//return View();
}
[HttpPost]
public ActionResult search(int id,string searchString,Student students)
{
var query = db.students.Where(d => d.No == id).AsQueryable();
if (!string.IsNullOrEmpty(searchString))
{
query = query.Where(d => d.Name.Contains(searchs)); // generate an error local variable 'searchs' before it is declared.
}
var searchs = query.ToList();
return View("index",searchs);
}
}
Now how would I query for an id and a name at the same time?
update your controller
public class CrudManuallyController : Controller
{
public ActionResult Index()
{
return View(db.manages.ToList());
//return View();
}
[HttpPost]
public ActionResult search(int? id, string searchString,Student students)
{
//Lambda Linq to entity does not support Int32
//var search = (from d in db.students where d.No == Convert.ToInt32(id) && d.Name == id select d).ToList();
//var search = db.students.Where(d => d.No == Convert.ToInt32(id) && d.Name == id).ToList();
query = db.students.AsQueryable();
if (id.HasValue)
{
var studentId = id.Value;
query = query.Where(d => d.No == studentId);
}
if (!string.IsNullOrEmpty(searchString))
query = query.Where(d => d.Name.Contains(searchString));
var search = query.ToList();
return View("index",search);
}
}
update your .cshtml
#using (Html.BeginForm("search", "CrudManually", FormMethod.Post))
{
#Html.TextBox("id")
#Html.TextBox("searchString")
<br/>
<input type="submit" value="Search"/>
}
You can get 2 way
list.Where(i => i.Property == value).FirstOrDefault(); // C# 3.0+
list.Find(i => i.Property == value); // C# 3.0+
if you find any item, you can get that. If you dont find an item, you get null.
Tell me if you resolve :)

Exception occurred in the view

I get an exception
Object reference not set to an instance of an object
in ASP.NET MVC when I post form-data with more than one models.
This is my "ViewModel" class:
public class CustomerViewModel
{
public Customer Customer { get; set; }
public IEnumerable<tblGender> Genders { get; set; }
public IEnumerable<tblCountry> Countries { get; set; }
}
This is the Edit action method:
[HttpGet]
public ActionResult Edit(int id)
{
var customer = _context.Customers
.FirstOrDefault(c => c.Id == id);
var viewModel = new CustomerViewModel()
{
Customer = customer,
Genders = _context.tblGenders.ToList(),
Countries = _context.tblCountries.ToList()
};
return View("Edit",viewModel);
}
[HttpPost]
public ActionResult Edit(Customer customer)
{
var cust = _context.Customers.Single(c => c.Id == customer.Id);
TryUpdateModel(cust);
_context.SaveChanges();
return RedirectToAction("Index", "Customer");
}
Create.cshtml:
The error occurs in this section
<div class="form-group">
#Html.LabelFor(m => m.Customer.Gender)
#Html.DropDownListFor(m => m.Customer.Gender, new SelectList(Model.Genders, "Id", "GenderName"), "Select Gender", new { #class = "form-control" })
</div>
In this piece of code, your variable customer can be null:
var customer = _context.Customers.FirstOrDefault(c => c.Id == id);
In this piece of code, you are assigning that very variable to your model.Customer:
var viewModel = new CustomerViewModel()
{
Customer = customer,
In this piece of code, you are using model.Customer as if you are sure it is not null:
#Html.LabelFor(m => m.Customer.Gender)
Out of many other possibilities, this is the most obvious null-ref I can find.
To fix it you can do something like this:
var viewModel = new CustomerViewModel()
{
Customer = customer ?? new Customer(),
or this:
var customer = _context.Customers.FirstOrDefault(c => c.Id == id);
if (customer == null) {
return view("CustomerNotFound"); //or some other way to display your error
}
Regarding the Object reference exception. Have you created instances of the objects that you're using?
e.g:
private readonly CustomerViewModel _customerViewModel;
_customerViewModel = new CustomerViewModel();

modelBinding works when using model but not with viewmodel

I'm trying to get a dropdown show the right value when editing using a viewmodel but it only works when i pass the complete model to the view.
When I do it like this and there is already a contact selected it shows that contact in the edit screen.
Model
public class ClientModel
{
public int ID { get; set; }
public int ContactID { get; set; }
//Other atributes
}
View EditContact
#model Project.Models.ClientModel
#Html.DropDownListFor(model => model.ContactID , (SelectList)ViewBag.ContactID, "select a contact")
Controller
public ActionResult EditContact(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var Contact = db.Contacts.ToList();
ViewBagID.Contact = new SelectList(Contact.AsEnumerable(), "ID", "name", "Contact");
ClientModel model= db.ClientModel.Find(id);
return View(model);
}
But when I do it like this and there is already a contact selected the dropdownlist shows select contact.
Model
public class ClientModel
{
public int ID { get; set; }
public int ContactID { get; set; }
//Other atributes
}
ViewModel
public class ClientEditContactModel
{
public int ID { get; set; }
public int ContactID { get; set; }
}
View EditContact
#model Project.Models.ClientEditContactModel
#Html.DropDownListFor(model => model.ContactID, (SelectList)ViewBag.ContactID, "select a contact")
Controller
public ActionResult EditContact(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var Contact = db.Contacts.ToList();
ViewBag.ContactID = new SelectList(Contact.AsEnumerable(), "ID", "name", "Contact");
ClientModel client= db.ClientModel.Find(id);
ClientEditContactModel model = new ClientEditContactModel();
model.ID = client.ID;
model.ContactID = client.ContactID
return View(model);
}
How do i fix this with the viewmodel?
Edit
I've made some typo's in my code so I fixed them but because of them i found the answer see below.
I found the answer after some more research here https://stackoverflow.com/a/11949123/4252392.
The problem was that ViewBag's name is the same as the model's property.
So i changed the Viewbag's name.
New Controller
public ActionResult EditContact(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var Contact = db.Contacts.ToList();
ViewBag.ContactIDList = new SelectList(Contact.AsEnumerable(), "ID",
"name", "Contact");
ClientModel client= db.ClientModel.Find(id);
ClientEditContactModel model = new ClientEditContactModel();
model.ID = client.ID;
model.ContactID = client.ContactID
return View(model);
}
New View
#model Project.Models.ClientEditContactModel
#Html.DropDownListFor(model => model.ContactID, (SelectList)ViewBag.ContactIDList,
"select a contact")
If you set selected value in ContactID property from dropdown so you need to set dropdown in view like below:
#model Project.Models.ClientEditContactModel
#Html.DropDownListFor(model => model.ContactID, (SelectList)ViewBag.Contact,
"select a contact")

Storing linq query results in Model

I am attempting to Query a database and store those results in a model, one of the columns is numerical and one is string data:
Model:
using System.Data.Entity;
namespace Portal.Models
{
public class CompanyListId
{
public int Id { get; set; }
public string CompanyName { get; set; }
}
public class CompanyListIdDbContext : DbContext
{
public DbSet<CompanyListId> Contacts { get; set; }
}
}
Controller:
public PartialViewResult SelectCompanyFromDropdown()
{
using (var dc = new CompanyListIdDbContext())
{
var content = from p in db.Companies
select new { p.CoId, p.CompanyName };
}
//I want to set Models ID = to each instance of coid
//Set Models CompanyName to each instance of companyname
return PartialView();
}
I am not sure where to go from here, I am attempting to make a drop down from this model.
I updated my code block to:
public PartialViewResult SelectCompanyFromDropdown()
{
using (var dc = new CompanyListIdDbContext())
{
var content = from p in db.Companies
select new CompanyListId
{
Id = p.CoId,
CompanyName = p.CompanyName
};
return PartialView(content.ToList());//giving an error
}
}
And my view to:
#model Portal.Models.CompanyListId
#Html.DropDownListFor(m => m.CompanyName, Model.CompanyName)
This also doesn't seem to work, I need to return my Model from the action I would think, that way the view can properly use the data.
You should project the result to your class CompanyListId
var content = from p in db.Companies
select new CompanyListId
{
Id = p.CoId,
CompanyName = p.CompanyName
};
EDIT:
I am not sure about the error, but you can try :
public PartialViewResult SelectCompanyFromDropdown()
{
List<CompanyListId> content = null;
using (var dc = new CompanyListIdDbContext())
{
content = (from p in db.Companies
select new CompanyListId
{
Id = p.CoId,
CompanyName = p.CompanyName
}).ToList();
}
return PartialView(content);
}
You can just select a new instance of your class like so:
var content = from p in db.Companies
select new CompanyListId
{
Id = p.CoId,
CompanyName = p.CompanyName
};

How to update a textarea in the current view on Submit in ASP.net MVC 3?

I have a page that has two drop down lists and based upon the selection of these two lists I would like to populate a textarea with some data on submit button press.
The behavior that I am seeing while debugging is that the page is rendered, I make my selections and press submit. The DataAccess returns the correct results and the View returns, but with an exception "There is no ViewData item of type 'IEnumerable' that has the key 'People'.
I can see that I could re-setup the drop down lists, but it feels like I'm approaching this incorrectly. Is there another approach for doing this sort of action in MVC 3?
public ActionResult Test()
{
//People for dropdownlist 1
var db = peopleRepository.People;
var query = db.Select(c => new {c.Id, c.Name});
ViewBag.People = new SelectList(query.AsEnumerable(), "Id", "Name");
//Elements for dropdownlist 2
var list = new Dictionary<string, string> {{"1", "Name"}, {"2", "Address"}, {"3", "Zip"}};
ViewBag.Elements = new SelectList(list, "Key", "Value");
return View();
}
// This part is what I'm confused about.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Test(string people, string elements)
{
if (ModelState.IsValid)
{
// Output from persistent storage query
var da = new DatabaseAccess(people, elements);
ViewBag.Results = da.Execute();
}
return View();
}
View:
#using (Html.BeginForm("Test", "Home", FormMethod.Post))
{
#Html.DropDownList("People", (SelectList)ViewBag.People, "--Select One--")
#Html.DropDownList("Elements", (SelectList)ViewBag.Elements, "--Select One--")
#Html.TextArea("Results", (string)ViewBag.Results, 10, 120, "")
}
Here is how I would quickly construct it :
Model :
public class People
{
public int Id { get; set; }
public string Name { get; set; }
}
ViewModel (everything needed by the view):
public class TestViewModel
{
public int SelectedPeopleId { get; set; }
public string SelectedElementId { get; set; }
public SelectList People { get; set; }
public SelectList Elements { get; set; }
public String Results { get; set; }
}
Controller (used Index as the default Action, create an init function for the view model that can be adapted)to anything more appropriate :
public class HomeController : Controller
{
private static TestViewModel InitTestVM()
{
//People for dropdownlist 1
var db = new List<People>();//peopleRepository.People;
db.Add(new People { Id = 1, Name = "Name 1" });
db.Add(new People { Id = 2, Name = "Name 2" });
var query = db.Select(c => new { c.Id, c.Name });
//Elements for dropdownlist 2
var list = new Dictionary<string, string> { { "1", "Name" }, { "2", "Address" }, { "3", "Zip" } };
TestViewModel testVM = new TestViewModel
{
People = new SelectList(query.AsEnumerable(), "Id", "Name"),
Elements = new SelectList(list, "Key", "Value")
};
return testVM;
}
public ActionResult Index()
{
return View(InitTestVM());
}
// This part is what I'm confused about.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(TestViewModel testVM)
{
var vm = InitTestVM();
if (ModelState.IsValid && testVM != null)
{
ModelState.Clear();
// Output from persistent storage query
//var da = new DatabaseAccess(people, elements);
vm.Results = "sfdfsdfsdfsdfsdfsdfsdfsdf";//da.Execute();
vm.SelectedElementId = testVM.SelectedElementId;
vm.SelectedPeopleId = testVM.SelectedPeopleId;
return View(vm);
}
return View(vm);
}
}
And finally the View :
#model ViewModels.TestViewModel
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.DropDownListFor(m => m.SelectedPeopleId, Model.People, "--Select One--")
#Html.DropDownListFor(m => m.SelectedElementId, Model.Elements, "--Select One--")
#Html.TextAreaFor(m => m.Results, 10, 120, "")
<input type="submit" value="Test" />
}

Categories

Resources