Search filter using multiple fields showing error in ASP.NET MVC with Entitiy Framework - asp.net-mvc

I am trying to apply search filter in ASP.NET MVC using multiple fields for which I have used view models. I have reached close to it but it is showing this error:
The model item passed into the dictionary is of type 'System.Data.Entity.DbSet`1[HMS.Models.tblPatient]', but this dictionary requires a model item of type 'HMS.ViewModels.SearchViewModel'
I don't know what I am doing wrong.
Here is my code:
SearchController.cs:
public ActionResult Index(SearchViewModel searchModel)
{
var search = new SearchDAL();
var model = search.GetSearchResults(searchModel);
return View(model);
}
ViewModel.cs:
public class SearchViewModel
{
public SearchViewModel()
{
PatientsSearch = new List<SearchResult>();
}
public int? Patient_ID { set; get; }
public string Patient_Name { set; get; }
public string Patient_Address { set; get; }
public string Contact_Number { set; get; }
public int Age { set; get; }
public string Gender { set; get; }
public List<SearchResult> PatientsSearch { set; get; }
}
public class SearchResult
{
public int? Patient_ID { set; get; }
public string Patient_Name { set; get; }
public string Patient_Address { set; get; }
public string Contact_Number { set; get; }
public int Age { set; get; }
public string Gender { set; get; }
}
SearchDAL.cs:
public class SearchDAL
{
private HMS_DBEntity Context;
public SearchDAL()
{
Context = new HMS_DBEntity();
}
public IQueryable<tblPatient> GetSearchResults(SearchViewModel searchModel)
{
var result = Context.tblPatients.AsQueryable();
if (searchModel != null)
{
if (searchModel.Patient_ID.HasValue)
result = result.Where(x => x.Patient_id == searchModel.Patient_ID);
if (!string.IsNullOrEmpty(searchModel.Patient_Name))
result = result.Where(x => x.Patient_Name.Contains(searchModel.Patient_Name));
if (!string.IsNullOrEmpty(searchModel.Patient_Address))
result = result.Where(x => x.Patient_address.Contains(searchModel.Patient_Address));
if (!string.IsNullOrEmpty(searchModel.Contact_Number))
result = result.Where(x => x.Contact_no.Contains(searchModel.Contact_Number));
}
return result;
}
}
Index.cshtml:
#using HMS.ViewModels
#model HMS.ViewModels.SearchViewModel
#*#model HMS.Models.tblPatient*#
#{
ViewBag.Title = "Index";
}
<section class="content">
#using (Html.BeginForm("Index", "Search", FormMethod.Get))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(false, "", new { #class = "text-danger" })
<div class="container-fluid">
<div class="block-header">
<h2>Patients Record</h2>
</div>
<div class="row clearfix">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="card">
<div class="body">
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.TextBoxFor(x => x.Patient_ID, new { #type = "Text", #class = "form-control", #id = "PatientID", #placeholder = "Patiend ID" })
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.TextBoxFor(x => x.Patient_Name, new { #type = "Text", #class = "form-control", #id = "PatientName", #placeholder = "Patiend Name" })
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.TextBoxFor(x => x.Patient_Address, new { #type = "Text", #class = "form-control", #id = "PatientAddress", #placeholder = "Patient Address" })
</div>
</div>
</div>
<div class="col-sm-6 col-md-6 col-lg-6">
<div class="form-group">
<div class="form-line">
#Html.TextBoxFor(x => x.Contact_Number, new { #type = "Text", #class = "form-control", #id = "ContactNo", #placeholder = "Contact Number" })
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6 col-md-6 col-lg-6">
<input type="submit" id="Submit" class="btn btn-raised g-bg-cyan waves-effect" value="Search" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
<div class="row clearfix">
<div class="container-fluid">
<div class="col-lg-12 col-md-12 col-sm-12">
<div class="card">
<div class="body table-responsive">
<table class="table table-bordered table-striped table-hover js-basic-example dataTable">
<tr>
<th>
#Html.DisplayNameFor(model => model.Patient_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Patient_Address)
</th>
<th>
#Html.DisplayNameFor(model => model.Contact_Number)
</th>
<th>
#Html.DisplayNameFor(model => model.Age)
</th>
<th>
#Html.DisplayNameFor(model => model.Gender)
</th>
<th></th>
</tr>
#{
if (Model.PatientsSearch != null && Model.PatientsSearch.Count > 0)
{
foreach (var item in Model.PatientsSearch)
{
<tr>
<td>#item.Patient_Name</td>
<td>#item.Patient_Address</td>
<td>#item.Contact_Number</td>
<td>#item.Age</td>
<td>#item.Gender</td>
</tr>
}
}
}
</table>
</div>

The error message is clear. Your model defined in view Index.cshtml is
#model HMS.ViewModels.SearchViewModel
But the data you pass to the view is result of GetSearchResults, which is System.Data.Entity.DbSet`1[HMS.Models.tblPatient]
var model = search.GetSearchResults(searchModel);
return View(model);
I think you know how to make it works now.

It's a type mismatch issue at:
return View(model);
So, inside GetSearchResults method, make following change while returning the result object:
result = new List<SearchViewModel>(result);
return result;
And, change your return type of GetSearchResults() method from IQueryable to List
public List<SearchViewModel> GetSearchResults(SearchViewModel searchModel)

Related

How to find an item in my database?

So i want to create a person and add it to my table if i dont have the same name already in my table. i have this code in my controller
hesaplamaEntities hsb = new hesaplamaEntities();
[HttpPost]
public ActionResult Create(MyTable p)
{
MyTable obj = hsb.MyTable.Find(p);
if (obj.propname == null)
{
hsb.MyTable.Add(p);
hsb.SaveChanges();
return RedirectToAction("Create", "Home");
}
else
{
return HttpNotFound();
}
and this is my View :
#using (Html.BeginForm("Create", "Home", FormMethod.Post, new { #class =
"form-horizontal", enctype = "multipart/form-data" }))
{
<div class="row">
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-12">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
#Html.TextBoxFor(m => m.propname, new { #class = "form-control" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="col-sm-2 control-label">kod</label>
<div class="col-sm-10">
#Html.TextAreaFor(m => m.propkod, new { #class = "form-control" })
</div>
</div>
</div>
</div>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-sm-9 col-sm-offset-3">
<div class="btn-toolbar pull-right">
<input type="submit" value="save" class="btn btn-primary" />
</div>
</div>
</div>
</div>
}
and this is my Model :
public partial class MyTable
{
public int ID { get; set; }
public string propkod { get; set; }
public string propname { get; set; }
}
i am having this error when i am trying to add person :
he specified parameter type 'WebApplication7.Models.MyTable' is not valid. Only scalar types, such as System.Int32, System.Decimal, System.DateTime, and System.Guid, are supported.
and its showing me the error in this line : HesapTemel obj = hsb.HesapTemels.Find(p);
what is the probleme exactly ?

POST Method doesn't work MVC 4

I try Create a new article in my table art, but the POST Method doesn't work, i don't now why, , Edit Article working perfectly, i read many post form that topic and nothing, i hope anyone can help me
Model
public class Art
{
[Key]
public int idArt { get; set; }
[DisplayName("Codigo Artículo")]
[Required(ErrorMessage = "Codigo Artículo Requerido")]
[MaxLength(30)]
public string co_art { get; set; }
[DisplayName("Tipo Articulo")]
[ForeignKey("TypeArticles")]
[Required(ErrorMessage = "Tipo Artículo Requerido")]
public int IDType { get; set; }
public virtual TypeArticles TypeArticles { get; set; }
[DisplayName("Descripción")]
[Required(ErrorMessage = "Descripción Artículo Requerido")]
[MaxLength(150)]
public string des_art { get; set; }
[DisplayName("Modelo")]
[Required(ErrorMessage = "Modelo Artículo Requerido")]
[MaxLength(50)]
public string modelo { get; set; }
[DisplayName("Referencia")]
[MaxLength(50)]
[Required(ErrorMessage = "Referencia Artículo Requerido")]
public string referencia { get; set; }
[DisplayName("Linea Artículo")]
[ForeignKey("Linea")]
[Required(ErrorMessage = "Linea Artículo Requerido")]
public int IdLinea { get; set; }
public virtual Linea Linea { get; set; }
[DisplayName("Categoria Artículo")]
[ForeignKey("Categoria")]
[Required(ErrorMessage = "Categoria Artículo Requerido")]
public int idCat { get; set; }
public virtual Categoria Categoria { get; set; }
[DisplayName("Precio Venta")]
[Range(0.01, 999999999, ErrorMessage = "Precio debe estar entre 0.01 y 999999999")]
public double Price { get; set; }
[MaxLength(1024)]
[DisplayName("Info. Adicional")]
public string Adicional { get; set; }
[MaxLength(100)]
public string Photo { get; set; }
}
Controller POST Method
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(Art artmodels)
{
ViewBag.idLinea = new SelectList(db.Linea.OrderBy(c => c.des_lin), "IdLinea", "des_lin");
ViewBag.IdCat = new SelectList(db.Categorias.OrderBy(c => c.des_cat), "IdCat", "des_cat");
ViewBag.IDType = new SelectList(db.TypeArticles.OrderBy(c => c.TypeDesc), "IDType", "TypeDesc");
if (ModelState.IsValid)
{
var art_exists = (from inv in db.Art where inv.co_art == artmodels.co_art.Trim() select inv).FirstOrDefault();
if (art_exists != null)
{
ModelState.AddModelError("co_art", "Codigo de Articulo ya Existe");
return View(artmodels);
}
db.Art.Add(artmodels);
db.SaveChanges();
///
//int currentPageIndex = page.HasValue ? page.Value - 1 : 0;
//var articulos = db.Art;
//IPagedList<Art> art_paged = null;
//art_paged = articulos.OrderBy(i => i.co_art).ToPagedList(currentPageIndex, (pagesize.HasValue) ? pagesize.Value : defaultPageSize);
return RedirectToAction("Edit", "Articulos", new {id = artmodels.idArt });
}
this.Response.StatusCode = 400;
return View(artmodels);
}
View
#model mvcAmerica.Models.Art
#{
ViewBag.Title = "Creacion";
}
<h1><small>Creación Articulos</small></h1>
#using (Html.BeginForm("Create", "Articulos", FormMethod.Post))
{
#Html.ValidationSummary(true)
<text>
#{Html.RenderPartial("CreateOrEditArticulos", Model);}
</text>
}
RenderPartial
#model mvcAmerica.Models.Art
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
#Html.HiddenFor(model => model.idArt)
<div class="clearfix">
#Html.LabelFor(model => model.co_art)
<div class="input">
#Html.EditorFor(model => model.co_art)
#Html.ValidationMessageFor(model => model.co_art)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.des_art)
<div class="input">
#Html.EditorFor(model => model.des_art)
#Html.ValidationMessageFor(model => model.des_art)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.IDType, "Tipo Articulo")
<div class="input chosen-select">
#Html.DropDownList("IDType", String.Empty)
#Html.ValidationMessageFor(model => model.IDType)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.modelo)
<div class="input">
#Html.EditorFor(model => model.modelo)
#Html.ValidationMessageFor(model => model.modelo)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.referencia)
<div class="input">
#Html.EditorFor(model => model.referencia)
#Html.ValidationMessageFor(model => model.referencia)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.IdLinea)
<div class="input chosen-select">
#Html.DropDownList("IdLinea", String.Empty)
#Html.ValidationMessageFor(model => model.IdLinea)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.idCat)
<div class="input chosen-select">
#Html.DropDownList("IdCat", String.Empty)
#Html.ValidationMessageFor(model => model.idCat)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.Price)
<div class="input">
#Html.EditorFor(model => model.Price)
#Html.ValidationMessageFor(model => model.Price)
</div>
</div>
<div class="clearfix">
#Html.LabelFor(model => model.Adicional)
<div class="input">
#Html.EditorFor(model => model.Adicional)
#Html.ValidationMessageFor(model => model.Adicional)
</div>
</div>
<div class="actions">
<input type="submit" class="btn primary" value="Guardar" />
#Html.ActionLink("Listado", "Index", null, new { #class = "btn" })
</div>
</fieldset>
}
Thanks for the help that bring me in this problem...
You have nested forms in your code which is causing this issue. The Submit button is in the inner but it dies not have any Controller and Anction methods to call, So it's not post the data to any method.
So you need to change this code something like this:
View
#model mvcAmerica.Models.Art
#{
ViewBag.Title = "Creacion";
}
<h1><small>Creación Articulos</small></h1>
//the commented line should go to the partial view
//#using (Html.BeginForm("Create", "Articulos", FormMethod.Post))
//{
// #Html.ValidationSummary(true)
<text>
#{Html.RenderPartial("CreateOrEditArticulos", Model);}
</text>
RenderPartial
#model mvcAmerica.Models.Art
#using (Html.BeginForm("Create", "Articulos", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
// rest of the code is as it is
}

Populating List of values from multiple models

How to create a List of values that to be referred by multiple models/screen?
I have created a model as ListValues, which will contains 2 fields (ID, Name) and I want that to be called by all of my models, what could be the best way. I do not want to loose on binding as well.
Have all of your models inherit from ListValues. You might want to rename the ListValues, which is now a base class, to something more descriptive like ModelBase.
Here's an example:
ModelBase.cs
namespace ListValuesTest.Models
{
public class ModelBase
{
public int ID { get; set; }
public string Name { get; set; }
}
public class Employee : ModelBase
{
public string Department { get; set; }
}
public class Customer : ModelBase
{
public string Application { get; set; }
}
}
HomeController.cs
namespace ListValuesTest.Controllers
{
public class HomeController : Controller
{
public ActionResult EmployeeOfTheMonth()
{
ListValuesTest.Models.Employee NumberOneEmployee = new Models.Employee();
NumberOneEmployee.ID = 1;
NumberOneEmployee.Name = "Brian";
NumberOneEmployee.Department = "IT";
return View(NumberOneEmployee);
}
public ActionResult CustomerOfTheMonth()
{
ListValuesTest.Models.Customer NumberOneCustomer = new Models.Customer();
NumberOneCustomer.ID = 1;
NumberOneCustomer.Name = "Microsoft";
NumberOneCustomer.Application = "Visual Studio";
return View(NumberOneCustomer);
}
}
}
EmployeeOfTheMonth.cshtml
#model ListValuesTest.Models.Employee
#{
ViewBag.Title = "EmployeeOfTheMonth";
}
<h2>EmployeeOfTheMonth</h2>
<fieldset>
<legend>Employee</legend>
<div class="display-label">
#Html.DisplayNameFor(model => model.Department)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Department)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.Name)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Name)
</div>
</fieldset>
<p>
#Html.ActionLink("Edit", "Edit", new { id=Model.ID }) |
#Html.ActionLink("Back to List", "Index")
</p>
CustomerOfTheMonth.cshtml
#model ListValuesTest.Models.Customer
#{
ViewBag.Title = "CustomerOfTheMonth";
}
<h2>CustomerOfTheMonth</h2>
<fieldset>
<legend>Customer</legend>
<div class="display-label">
#Html.DisplayNameFor(model => model.Application)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Application)
</div>
<div class="display-label">
#Html.DisplayNameFor(model => model.Name)
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Name)
</div>
</fieldset>
<p>
#Html.ActionLink("Edit", "Edit", new { id=Model.ID }) |
#Html.ActionLink("Back to List", "Index")
</p>
i think ViewModel will be your best solution,look on the web for solutions using any view model...if you face any difficulty,come to us then with code

pass value of List

i try to show my data using viewmodel, but i have error like this
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[XNet.Repository.Model.FacilityViewModel]', but this dictionary requires a model item of type 'XNet.Repository.Model.FacilityViewModel'.
how i can solve my problem??
this my code
my service
public List<FacilityViewModel> GetViewHotel(int HotelID)
{
List<Hotel> Hotels = (from d in _HotelRepository.All()
where d.HotelID == HotelID
select d).ToList();
List<FacilityViewModel> facilityViewModel = new List<FacilityViewModel>();
foreach (Hotel hotel in Hotels)
{
facilityViewModel.Add(new FacilityViewModel
{
HotelID = HotelID,
HotelName = hotel.HotelName,
Address1 = hotel.Address1,
Address2 = hotel.Address2,
HotelDescription = hotel.HotelDescription,
HotelInformation = hotel.HotelInformation,
});
}
return facilityViewModel;
}
my controller
public ActionResult Index()
{
//var x = _hotelService.GetByID(_HotelID);
List<FacilityViewModel> facilityViewModel = _viewService.GetViewHotel(_HotelID);
return View(facilityViewModel);
}
my viewmodel
public class FacilityViewModel
{
public int HotelID { get; set; }
public string HotelName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string HotelDescription { get; set; }
public string HotelInformation { get; set; }
}
my view
#model XNet.Repository.Model.FacilityViewModel
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<fieldset>
<legend></legend>
<div class="display-label">
#Html.Label("Hotel ID")
</div>
<div class="display-field">
#Html.DisplayFor(model => model.HotelID)
</div>
<br />
<div class="display-label">
#Html.Label("Hotel Name")
</div>
<div class="display-field">
#Html.DisplayFor(model => model.HotelName)
</div>
<br />
<div class="display-label">
#Html.Label("Address 1")
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Address1)
</div>
<br />
<div class="display-label">
#Html.Label("Address 2")
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Address2)
</div>
<br />
<div class="display-label">
#Html.Label("Hotel Description")
</div>
<div class="display-field">
#Html.DisplayFor(model => model.HotelDescription)
</div>
<br />
<div class="display-label">
#Html.Label("Hotel Information")
</div>
<div class="display-field">
#Html.DisplayFor(model => model.HotelInformation)
</div>
<br />
<br />
</fieldset>
<br />
<input style="width:100px;" type="button" title="EditHotelDetail" value="EditDetails" onclick="location.href='#Url.Action("Edit", "Hotel", new { HotelID = Model.HotelID})'" />
The error message says it all.
Your view has the model typed as just the instance of FacilityViewModel while you are returning a List of FacilityViewModel from the action
In your view:
#model XNet.Repository.Model.FacilityViewModel
In your action:
List<FacilityViewModel> facilityViewModel = _viewService.GetViewHotel(_HotelID);
return View(facilityViewModel); //<-- This is a list.
Either
return View(facilityViewModel.First()) //just an example to show a single instance.
or
Modify the code to handle a list in the view.
Your declaring you model for the View as:
#model XNet.Repository.Model.FacilityViewModel
Instead of:
#model List<XNet.Repository.Model.FacilityViewModel>
In your controller's action you are returning a List to the View.
Either modify the model to take a List<FacilityViewMOdel> in the View or return a single FacilityViewModel to the View.
return View(facilityViewModel.FirstOrDefault());

After submit a form in a Area not displayed none of validation message?

I have a area and at this area i have a PostController, and a action with Add name for GET method and a action with Add name for POST method,after submit form i add error to modelstate BUT after postback,not displayed none of validation message and staus code is:301 Moved Permanently !!!
my viewmodel:
public class NewPostViewModel
{
[Required(ErrorMessage = "Please enter title.")]
public string Title { get; set; }
[AllowHtml]
[Required(ErrorMessage = "Please enter article content.")]
public string Content { get; set; }
[Required(ErrorMessage = "Please enter a tag.")]
public string Tags { get; set; }
public bool PublishNow { get; set; }
public string PublishDate { get; set; }
public string PublishTime { get; set; }
}
my view:
#model Soleimanzadeh.Models.ViewModels.NewPostViewModel
#{
ViewBag.Title = "Add";
Layout = MVC.Admin.Shared.Views.BaseLayout;
}
#using (Html.BeginForm(MVC.Admin.Post.Add(), FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(false, null, new { #class = "alert" })
<div class="row-fluid">
<div class="span9">
<div class="row-fluid">
<div class="span8">
#Html.TextBoxFor(np => np.Title, new { #class = "span12", placeholder = "Title" })
#Html.ValidationMessageFor(model=>model.Title)
</div>
</div>
<div class="row-fluid">
<div class="span12">
#Html.TextAreaFor(np => np.Content)
#Html.ValidationMessageFor(model=>model.Content)
</div>
</div>
</div>
<div class="span3">
<div class="row-fluid">
<div class="post-options-container">
<div class="header">
Tags
</div>
<div class="content">
<input type="text" placeholder="tags" class="tagManager" style="width: 100px;" />
</div>
</div>
</div>
<div class="row-fluid">
<div class="post-options-container">
<div class="header">
Status
</div>
<div class="content">
<label class="checkbox">
#Html.CheckBoxFor(np => np.PublishNow)
Publish Now?
</label>
<div>
Publish Date:
#Html.TextBoxFor(np => np.PublishDate, new { #class = "calcInput" })
</div>
<div>
Publish Time:
#Html.TextBoxFor(np => np.PublishTime, new { #class = "timeInput" })
</div>
<div>
<input type="submit" value="Save"/>
</div>
</div>
</div>
</div>
</div>
</div>
}
#*some scripts here*#
my controller:
public partial class PostController : Controller
{
public virtual ActionResult Add()
{
var newPost = new NewPostViewModel();
return View(MVC.Admin.Post.Views.Add, newPost);
}
[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult Add(NewPostViewModel post)
{
ModelState.AddModelError("Content","Wrong");
return this.View(MVC.Admin.Post.Views.Add, post);
}
}
Also i use redactor html editor for Content.
Solution:
i use http://lowercaseroutesmvc.codeplex.com/ for convert urls to lowercase,but i not enabled this tool in area section and page redirectd after submit form.

Resources