Populating List of values from multiple models - asp.net-mvc

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

Related

Search filter using multiple fields showing error in ASP.NET MVC with Entitiy Framework

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)

Passing values from the view to the controller in MVC4

I'm trying to pass these textbox values to the controller:
#model DTOs.QuestionDTO
#{
ViewBag.Title = "AddQuestion";
}
<h2>AddQuestion</h2>
#using (Html.BeginForm("AddQuestionDB", "Exam"))
{
<fieldset>
<legend>Add Question</legend>
<div class="editor-label">
#Html.LabelFor(model => model.QuestionDes)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.QuestionDes , new { #id="question" , #name="question"})
#Html.ValidationMessageFor(model => model.QuestionDes)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Answer1)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Answer1 , new { #id="a1" , #name="a1"})
#Html.ValidationMessageFor(model => model.Answer1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Answer2)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Answer2 , new { #id="a2" , #name="a2"})
#Html.ValidationMessageFor(model => model.Answer2)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Answer3)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Answer3 , new { #id="a3" , #name="a3"})
#Html.ValidationMessageFor(model => model.Answer3)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Answer4)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Answer4 , new { #id="a4" , #name="a4"})
#Html.ValidationMessageFor(model => model.Answer4)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Correct)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Correct , new { #id="correct" , #name="correct"})
#Html.ValidationMessageFor(model => model.Correct)
</div>
<p>
<input type="submit" value="Add" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to Login", "Login")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
this is how my controller method looks like:
public ActionResult AddQuestionDB(string question, string a1, string a2, string a3, string a4, string correct)
{
ViewBag.a1 = a1;
ViewBag.a2 = a2;
ViewBag.a3 = a3;
ViewBag.a4 = a4;
ViewBag.correct = correct;
return View();
}
And i have created a View to display this Viewbag variables... but these variables wont come up.
it seem to be that these variables are null..
#{
ViewBag.Title = "AddQuestionDB";
}
<h2>AddQuestionDB</h2>
<p>#Session["q"]</p>
<p>#ViewBag.question</p>
<p>#ViewBag.a1</p>
<p>#ViewBag.a2</p>
<p>#ViewBag.a3</p>
<p>#ViewBag.a4</p>
<p>#ViewBag.correct</p>
this is how my DTO looks like:
namespace DTOs
{
public class QuestionDTO
{
public int ID { get; set; }
public string QuestionDes { get; set; }
public string Answer1 { get; set; }
public string Answer2 { get; set; }
public string Answer3 { get; set; }
public string Answer4 { get; set; }
public int Correct { get; set; }
}
}
Can you please explain, how i should do this??
thank you!!!
Instead of -
public ActionResult AddQuestionDB(string question, string a1, string a2, string a3, string a4, string correct)
{
// Your custom code
return View();
}
have this code -
public ActionResult AddQuestionDB(QuestionDTO question)
{
// Use 'question' object here to get posted values.
return View();
}
I replicated your scenario in a small sample project on my local, here is the outcome when I debugged the code with breakpoint -
Html.EditorFor does not support setting attributes, which is why your original code wasn't working. The name attribute didn't match the parameter names in your controller action, so they were assigned null.
You can either use #ramiramilu's answer, or you could use TextBoxFor instead:
#Html.TextBoxFor(model => model.Correct , new { id="correct" , Name="correct"})
(Note that Name must be capitalized in order for this to work).
Example: https://dotnetfiddle.net/ZfzCaZ

Just added comment shows at different page, but not at the same page

When Im trying to add a comment at Details page it send to this page:
https://onedrive.live.com/redir?resid=ED946C8D08765D6F%21107
My Controller:
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Student student = _db.Students.Include(m => m.Comments).SingleOrDefault(x => x.ID == id);
if (student == null)
{
return HttpNotFound();
}
//var enrollments = new Enrollment { };
var model = new DetailsViewModel
{
Comment = new Comment(),
Student = student,
Comments = student.Comments.OrderBy(c => c.Id).ToList()
};
}
public ActionResult AddComment(Comment comment, int commentId)
{
if (ModelState.IsValid && commentId > 0)
{
var commentToAdd = new Comment
{
Email = comment.Email,
CommentId = commentId,
Name = comment.Name,
Text = comment.Text,
};
_db.Comments.Add(commentToAdd);
_db.SaveChanges();
return PartialView("_Comment", commentToAdd);
}
return RedirectToAction("Index", "Student");
}
Details View:
#model ContosoUniversity.ViewModels.DetailsViewModel
#{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Student</h4>
<hr />
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(model => model.Student.LastName)
</dt>
<dd>
#Html.DisplayFor(model => model.Student.LastName)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Student.FirstMidName)
</dt>
<dd>
#Html.DisplayFor(model => model.Student.FirstMidName)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Student.EnrollmentDate)
</dt>
<dd>
#Html.DisplayFor(model => model.Student.EnrollmentDate)
</dd>
<dt>
#Html.DisplayNameFor(model => model.Student.Enrollments)
</dt>
<dd>
<table class="table">
<tr>
<th>Course Title</th>
<th>Grade</th>
</tr>
</table>
</dd>
</dl>
#using (Html.BeginForm("AddComment", "Student", FormMethod.Get))
{
<div class="form-horizontal">
<h4>Comments</h4>
<hr />
#Html.ValidationSummary(true)
<input type="hidden" value="#Model.Student.ID" name="commentId" />
<div class="form-group">
#Html.LabelFor(model => model.Comment.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comment.Name)
#Html.ValidationMessageFor(model => model.Comment.Name)
</div>
</div>
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Comment.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comment.Email)
#Html.ValidationMessageFor(model => model.Comment.Email)
</div>
</div>
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Comment.Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.Comment.Text)
#Html.ValidationMessageFor(model => model.Comment.Text)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Add Comment" class="btn btn-default" />
</div>
</div>
</div>
}
<div id="comments">
#foreach (var c in Model.Comments)
{
#Html.Partial("_Comment", c)
}
</div>
</div>
<p>
#Html.ActionLink("Edit", "Edit", new { id = Model.Student.ID }) |
#Html.ActionLink("Back to List", "Index")
</p>
DetailsViewModel:
public Student Student { get; set; }
public List<Comment> Comments { get; set; }
public Comment Comment { get; set; }
Comment Model:
public int Id { get; set; }
public int CommentId { get; set; }
public Student Student { get; set; }
[Required]
public string Name { get; set; }
[EmailAddress]
public string Email { get; set; }
[Required]
public string Text { get; set; }
Student Model:
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public List<Comment> Comments { get; set; }
I can't understand what is wrong it was work some time ago. Thank you
Because that's what you telling it to do with this line
return PartialView("_Comment", commentToAdd);
If you want to go back to the current page showing the newly added comment, then it should be
return RedirectToAction("Details", new { id = commentId });
and you doing a post so it should be FormMethod.Post in the BeginForm() method

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
}

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());

Resources