Unable to pass value to controller from view through viewmodel - c#

I'm pretty sure my brain is friend and this is something I'm going to laugh at tomorrow morning, but unfortunately I'm stuck on this portion and am asking for assistance.
I have a ViewModel:
public class HousingDetailsViewModel : AppViewModel
{
DataContext db = new DataContext();
public List<string> units { get; set; }
public List<AvailableHousing> availableHousings { get; set; }
public Person person { get; set; }
public OccupiedHousing currentHousing { get; set; }
public OccupiedHousing newHousing;
public HousingDetailsViewModel(int? id)
{
units = db.AvailableHousings.OrderBy(ah => ah.Unit).Select(h => h.Unit).Distinct().ToList();
availableHousings = db.AvailableHousings.Where(h => h.Available == true).OrderBy(h => h.Bed)
.OrderBy(h => h.Room).ToList();
currentHousing = db.OccupiedHousing.Include(o => o.AvailableHousing)
.Include(o => o.Person).Where(o => o.PersonID == id && o.CurrentHousing == true).FirstOrDefault();
person = db.Persons.Find(id);
newHousing = new OccupiedHousing();
}
}
My controller methods for this view:
public ActionResult Details(int? id)
{
return View(new HousingDetailsViewModel(id));
}
[HttpPost]
public ActionResult Move(OccupiedHousing newHousing, int? personID)
{
newHousing.PersonID = personID;
newHousing.DateArrived = DateTime.Now;
newHousing.CurrentHousing = true;
newHousing.AvailableHousingID = housingID;
db.OccupiedHousings.Add(newHousing);
db.SaveChanges();
return RedirectToAction("Index", new HousingViewModel());
}
And my form works fine for all of my fields except for 1, and that's the AvailableHousingID. I've tried setting a hidden value. I put a breakpoint where I set the value of the hidden field and I watched it change, but it didn't make it to the controller. So I changed it to a form submission and tried to catch it as a routevalue and that didn't work either. I'm at a loss, can anyone see where I'm going wrong?
EDIT: Adding View
#model AppName.ViewModels.HousingDetailsViewModel
#{
ViewBag.Title = "Housing Details";
}
#Html.BeginForm("Move", "Housing", new { personID = #Model.person.ID }, FormMethod.Post, new { })
<script>
function setID(id) {
$('#HiddenHousingID').val(id);
$('#HiddenSubmit').click();
}
</script>
<h2>Housing Details</h2>
<div class="row">
<div class="col-xs-12 container">
<div class="col-xs-5">
<img src="//placehold.it/150x200/77CCDD/66BBCC" class="img-responsive" />
</div>
<div class="col-xs-7">
<h4>#Model.person.ComboName</h4>
<h4>#Model.currentHousing.AvailableHousing.Unit - #Model.currentHousing.AvailableHousing.Room - #Model.currentHousing.AvailableHousing.Bed</h4>
<h4>#Model.person.DateOfBirth.Value.ToShortDateString()</h4>
#Html.HiddenFor(m => m.newHousing.AvailableHousingID, new { id = "HiddenHousingID", name = "newHousing.AvailableHousingID")}
</div>
</div>
</div>
<div class="row">
#foreach (var unit in Model.units)
{
<div class="col-xs-6">
<div class="panel panel-primary">
<div class="panel-heading">
<span class="panel-title">
#unit
</span>
</div>
<div class="panel-body">
<table id="MoveHousingTable" class="table table table-condensed table-striped">
<thead>
<tr>
<th>
Available Housing
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var housing in Model.availableHousings.Where(h => h.Unit == unit))
{
<tr>
<td>
#housing.Room -
#housing.Bed
</td>
<td>
<input type="button" value="Select" name="select" onclick="setID(#housing.ID)" />
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
}
</div>
<input type="submit" class="hidden" id="HiddenSubmit">
}

For the route :
#Html.BeginForm("Move", "Housing", new { personID = #Model.person.ID , housingID= #Model.newHousing.AvailableHousingID}, FormMethod.Post, new { })

Related

Access view model data in controller

In my application I have created a view model to show data in the View.
I created view model as this.
[NotMapped]
public class EmpExcelUploadViewModel {
public int CompanyId {
get;
set;
}
public int EmpNo {
get;
set;
}
public string EmpName {
get;
set;
}
public int EmpDep {
get;
set;
}
public int EmpDes {
get;
set;
}
}
In the controller I have assigned data to the view model and passed to the view. Just to show the data to the user, there is no editing or deleting data from the user view. That stage is works fine.
This is the view
#model IEnumerable
<Asp_PASMVC.ViewModels.EmpExcelUploadViewModel>
#{
ViewBag.Title = "Import";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div>
#using (Html.BeginForm("Import", "M_Employee", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="card card-primary">
<div class="card-header">
<h1 class="card-title"><b>Upload Employees from Excel</b></h1>
</div>
<div>
<br />
#Html.Raw(ViewBag.Error)
<h4><span>Select Excel File</span></h4>
<input type="file" name="excelFile" class="btn btn-warning" />
<br />
</div>
<div class="row">
<div class="col-md-1">
<br />
<br />
<input type="submit" value="Import" class="btn btn-info" />
</div>
<div class="col-md-1">
<br />
<br />
<input type="button" value="Upload" class="btn btn-success" onclick="location.href='#Url.Action("UploadEmployees", "M_Employee")'" />
</div>
</div>
<div class="card-body p-0">
<table class="table table-striped">
<tr>
<th>Company</th>
<th>EmpId</th>
<th>EmpName</th>
<th>Department</th>
<th>Dessignation</th>
</tr>
#if (ViewBag.EmpList != null)
{
foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CompanyId)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmpNo)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmpName)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmpDep)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmpDes)
</td>
</tr>
}
}
</table>
</div>
<!-- /.card-body -->
</div>
}
</div>
I want to know, when user clicks to the Upload button, that the data already in the view model I want to pass to the database. So how can I access the data already in the view model? I'm still learning MVC and I don't know if it's possible or not.
This is what I tried. Here in the empExcel getting error that EmpExcelUploadViewModel does not contain public instance.
public ActionResult UploadEmployees(EmpExcelUploadViewModel empExcel) {
try {
foreach(var item in empExcel) // error in empExcel {
int ComId = item.CompanyId;
int EmpNo = item.EmpNo;
string EmpName = item.EmpName;
int DepId = item.EmpDep;
int DesId = item.EmpDes;
var isEmployeeExists = (from e in db.CreateEmployee where e.EmpNo == EmpNo select e.Id).First();
if (isEmployeeExists != 0) {
M_Employee e = new M_Employee();
e.CompanyId = ComId;
e.EmpNo = EmpNo;
e.EmpName = EmpName;
e.DepId = DepId;
e.DesignId = DesId;
e.Status = true;
e.CreateDate = DateTime.Now;
e.CreateBy = int.Parse(((System.Security.Claims.ClaimsIdentity) User.Identity).FindFirst("UserId").Value);
db.CreateEmployee.Add(e);
db.SaveChanges();
} else {
M_Employee m_Employee = db.CreateEmployee.First(x => x.Id == isEmployeeExists);
m_Employee.DepId = DepId;
m_Employee.DesignId = DesId;
db.SaveChanges();
}
}
} catch (Exception ex) {
ViewBag.Error = "Error " + ex;
}
ViewBag.Error = "All Records uploaded to the database";
ViewBag.EmpList = null;
return View("Import");
}
}
Instead of saving data in the view, you should do it in the controller.
In the controller, if there's any error saving the data to the database, set a separate error flag indicating this. Then, the View uses this flag to determine what to display

How can i fill a table with values from a dropdownlist in ASP.NET Core MVC

I want to fill an html table with the selecteditem from a dropdownlist, I already passed the database data to this list, and I also get all the information of the selected value through an actionresult, so the thing I want is when I select an item, put it in the table, and do this every time I want so I can add various values at the same time. does anyone have any idea how to do it?
This is my model
public partial class Producto
{
public int Id { get; set; }
public string Nombre { get; set; }
public string Descripcion { get; set; }
public string Precio { get; set; }
[NotMapped]
public List <Producto> Listasnom { get; set; }
[NotMapped]
public IEnumerable < SelectListItem > ProductoListItems
{
get
{
return new SelectList(Listasnom ?? new List<Producto>(), "Id", "Nombre");
}
}
}
My controller
MyDbContext db = new MyDbContext();
[HttpGet]
public ActionResult Index()
{
return View(db.Pedido.ToList());
}
public ActionResult Create()
{
var lista = new Producto();
lista.Listasnom = db.Producto.ToList();
return View(lista);
}
[HttpPost]
public ActionResult Create(Producto producto)
{
var lista = new Producto();
lista.Listasnom = db.Producto.ToList();
var emp = lista.Listasnom.Where(e => e.Id == producto.Id).FirstOrDefault();
lista.Id = emp.Id;
lista.Nombre = emp.Nombre;
lista.Precio = emp.Precio;
return View(lista);
}
and my view:
#model punto.Models.Producto
<form class="form-horizontal" method="post" action="">
<div class="box-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-1 control-label">Producto</label>
<div class="col-sm-10">
#Html.DropDownListFor(model => model.Id, Model.ProductoListItems, "Elegir Producto", new { #class = "form-control"})
</div>
<button type="submit" class="btn btn-info">Agregar</button>
</div>
</form>
This is the table where I want to put the values
<table id="example1" class="table table-bordered table-responsive">
<thead>
<tr>
<th>Id</th>
<th>Producto</th>
<th>Precio</th>
</tr>
</thead>
<tbody>
<tr>
<td>#Html.DisplayFor(model => model.Id)</td>
<td>#Html.DisplayFor(model => model.Nombre)</td>
<td>#Html.DisplayFor(model => model.Precio) </td>
</tr>
</table>
I don't have any idea how to do it, if someone can help me.
If you want to select more products and store them in the table , you could try to use ajax as Nhien said :
View :
#model WebApplication2.Models.Producto
<div class="box-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-1 control-label">Producto</label>
<div class="col-sm-10">
#Html.DropDownListFor(model => model.Id, Model.ProductoListItems, "Elegir Producto", new { #class = "form-control",id="selectlist" })
</div>
<button type="submit" id="btnCreate" class="btn btn-info">Agregar</button>
</div>
</div>
<table id="example1" class="table table-bordered table-responsive">
<thead>
<tr>
<th>Id</th>
<th>Producto</th>
<th>Precio</th>
</tr>
</thead>
<tbody> </tbody>
</table>
#section Scripts
{
<script type="text/javascript">
$("#selectlist").change(function () {
var id = $("#selectlist").val()
$.ajax({
type: "get",
url: "/products/getproduct?id=" + id,
success: function (data) {
var tBody = $("#example1 > TBODY")[0];
var row = tBody.insertRow(-1);
//Add ID cell.
var cell = $(row.insertCell(0));
cell.html(data.id);
//Add Nombre cell.
cell = $(row.insertCell(1));
cell.html(data.nombre);
//Add Precio cell.
cell = $(row.insertCell(2));
cell.html(data.precio);
}
});
});
</script>
}
Controller :
public IActionResult GetProduct(int id)
{
var selectProduct = db.Producto.Find(id);
return Json(selectProduct);
}

How to send IEnumerable back from View to Controller

I'm pretty new to MVC and ASP.Net, my controller has 2 create methods for GET and POST. Through the Get method I'm generating a list and sending it into the view. In the view I'm making changes to a specific value in each var in the list and trying to send it back to the controller and the POST method.
When reaching the Post method, the value of the list is null.
The list I'm sending is a list of products and I'm using a view model to create a class with common values to pass through to the view.
To pass through the IEnumerable collection that was edited by the view I tried using BeginCollectionForm, setting the items through ViewBag, make changes to the model (#model IEnumerable<MarsBurgerV1.ViewModel.ItemVM>), but still each time the checkout button is being pressed the list in the Post method is NULL.
After a lot of tries and changes, currently my code looks as the following:
OrderController.cs (relevant parts)
public class OrderController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public ActionResult Create()
{
var meals = (from m in db.meals
select new ItemVM
{
Id = m.Id,
Name = m.Name,
Price = m.Price,
ItemType = "Meal",
ImageURL = m.ImageUrl,
Quantity = 0
}).ToList();
var drinks = (from d in db.drinks
select new ItemVM
{
Id = d.Id,
Name = d.Name,
Price = d.Price,
ItemType = "Drink",
Quantity = 0
}).ToList();
//More Like That....
List<ItemVM> items = new List<ItemVM>();
items.AddRange(meals);
items.AddRange(drinks);//More Like...
return View(items.ToList());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IEnumerable<ItemVM> items = null)
{
//Here items equals to null.
if (ModelState.IsValid)
{
//.....
}
return View();
}
Views/Order/Create.cshtml:
#model IEnumerable<***.ViewModel.ItemVM>
#{
ViewBag.Title = "Create";
var lst = Model.ToList();
ViewBag.List = Model.ToList();
}
<style>
tr td {
vertical-align: middle;
}
</style>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<h3> Order:</h3>
<table class="table table-condensed table-hover">
<tr calss="table-header">
<th>
#Html.DisplayName("Preview")
</th>
<th>
#Html.DisplayNameFor(m => m.Name)
</th>
<th>
#Html.DisplayNameFor(m => m.Price)
</th>
<th>
#Html.DisplayName("Quantity")
</th>
<th></th>
<th></th>
</tr>
#for (var i = 0; i < Model.Count(); i++)
{
<tr>
<td>
#if (Model.ElementAt(i).ImageURL != null)
{
<img src="#Url.Content(Model.ElementAt(i).ImageURL)" alt="IMAGES" height="100" width="100" />
}
</td>
<td>
#Html.DisplayFor(m => Model.ElementAt(i).Name)
</td>
<td>
#Html.DisplayFor(m => Model.ElementAt(i).Price)
</td>
<td>
<a type="button" class="btn btn-danger btn-xs" href="#">
<span class="glyphicon glyphicon-minus"></span>
</a>
#Html.EditorFor(l => lst[i].Quantity, new { htmlattribute = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => lst[i].Quantity, "", new { #class = "text-danger" })
<a type="button" class="btn btn-success btn-xs" id="plus" href="#">
<span class="glyphicon glyphicon-plus"></span>
</a>
</td>
</tr>
}
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Checkout" class="btn btn-primary"/>
</div>
</div>
}
ViewModel/ItemVM.cs:
namespace ***.ViewModel
{
public class ItemVM
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
[DataType(DataType.Currency)]
public double Price { get; set; }
[Required]
public string ItemType { get; set; }
public string ImageURL { get; set; }
[Required]
public int Quantity { get; set; }
}
}
In the end I want to use the "Create" (HttpPost method) to create a new order based on the values in the list received from the view.
What is the proper way of doing that and receiving the IEnumerable into the POST method?
Ok, I was finally able to make it work.
I've changed the #model to List Type,
Add the (actionName, Controller, FormMethod) to the HTML Helper Html.BeginForm,
Used Model[i] inside the loop to access variables and
marked all unchanged variables with
#Html.HiddenFor.
Create.cshtml:
#model List<MarsBurgerV1.ViewModel.ItemVM>
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm("Create","Order", FormMethod.Post))
{
#Html.AntiForgeryToken()
<h3> Order:</h3>
<table class="table table-condensed table-hover">
<tr calss="table-header">
<th>
#Html.DisplayName("Preview")
</th>
<th>
#Html.DisplayName("Name")
</th>
<th>
#Html.DisplayName("Price")
</th>
<th>
#Html.DisplayName("Quantity")
</th>
<th></th>
<th></th>
</tr>
#for (var i = 0; i < Model.Count(); i++)
{
<tr>
#Html.HiddenFor(m => Model[i].Id)
#Html.HiddenFor(m => Model[i].Type)
<td>
#Html.HiddenFor(m => Model[i].ImageURL)
#if (Model[i].ImageURL != null)
{
<img src="#Url.Content(Model[i].ImageURL)" alt="IMAGES" height="100" width="100" />
}
#Html.ValidationMessageFor(model => Model[i].ImageURL, "", new { #class = "label-control" })
</td>
<td>
#Html.HiddenFor(m => Model[i].Name)
#Html.DisplayFor(m => Model[i].Name)
#Html.ValidationMessageFor(model => Model[i].Name, "", new { #class = "label-control" })
</td>
<td>
#Html.HiddenFor(m => Model[i].Price)
#Html.DisplayFor(m => Model[i].Price, new { #class = "form-control" })
#Html.ValidationMessageFor(model => Model[i].Price, "", new { #class = "label-control" })
</td>
<td>
<a type="button" class="btn btn-danger btn-xs" href="#">
<span class="glyphicon glyphicon-minus"></span>
</a>
#Html.EditorFor(model => Model[i].Quantity, new { htmlattribute = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => Model[i].Quantity, "", new { #class = "text-danger" })
<a type="button" class="btn btn-success btn-xs" id="plus" href="#">
<span class="glyphicon glyphicon-plus"></span>
</a>
</td>
</tr>
}
</table>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" value="Checkout" class="btn btn-primary"/>
</div>
</div>
}
Thanks Everyone for the help.

How to pass List<Model> from view to controller [duplicate]

This question already has answers here:
Post an HTML Table to ADO.NET DataTable
(2 answers)
Closed 4 years ago.
Being a newbie in ASP.NET MVC framework, I am stack in sending a list of my model back to the controller via POST method. Below are samples of my source code and their explanation.
Model Class:
public class SiteIdentifier
{
[Display(Name = "Configuration Id")]
public string ConfigurationId { get; set; }
[Display(Name = "County")]
public string County { get; set; }
}
Controller (Get Method):
public ViewResult ViewNewSites()
{
List<SiteIdentifier> sites = new List<SiteIdentifier>()
{
new SiteIdentifier{ConfigurationId = 1, County = "County1"},
new SiteIdentifier{ConfigurationId = 2, County = "County2"},
new SiteIdentifier{ConfigurationId = 3, County = "County3"}
};
return View(sites);
}
View:
In this view, the user has to select some rows using checkbox and click on the submit button and the submit button has to pass those checked rows to controller.
#using HIE_Management_Studio.Common
#model IEnumerable<SiteIdentifier>
<!--If there is nothing to show, do not render this place.-->
#if (Model != null)
{
using (Html.BeginForm("CopyToProductionPOST", "CopyBySite",
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
}))
{
<div class="row">
<div class="col-md-12">
<div class="alert alert-info">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>
<input type="checkbox" id="chkSelectAll" />
</th>
<th>
#Html.DisplayNameFor(model => model.ConfigurationId)
</th>
<th>
#Html.DisplayNameFor(model => model.County)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td class="text-nowrap">
#Html.CheckBoxFor(modelItem => item.Selected, new { #class = "chkSelect" })
</td>
<td>
#Html.EditorFor(modelItem => item.ConfigurationId)
#Html.HiddenFor(modelItem => item.ConfigurationId)
</td>
<td>
#Html.EditorFor(modelItem => item.County)
#Html.HiddenFor(modelItem => item.County)
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" value="Submit" class="btn btn-info" />
</div>
</div>
<script>
$("#chkSelectAll").bind("change", function () {
$(".chkSelect").prop("checked", $(this).prop("checked"));
});
$(".chkSelect").bind("change", function () {
if (!$(this).prop("checked"))
$("#chkSelectAll").prop("checked", false);
});
$(".alert").hide().fadeIn("slow");
</script>
}
}
Controller (Post Method)
Now here is the post method in my controller that has to get all the selected rows from the view.
[HttpPost]
public ViewResult CopyToProductionPOST(List<SiteIdentifier> formCollection)
{
SiteIdentifier siteIdentifier = new SiteIdentifier();
// siteIdentifier.ConfigurationId = formCollection[0]["ConfigurationId"];
return View("CopyBySite");
}
I tried below link and it worked :)
https://www.c-sharpcorner.com/article/pass-dynamically-added-html-table-records-list-to-controller/

Foreach loop returning database search results to a view in cshtml

Cannot implicitly convert type
CourseSearchResultMode to IEnumerable. An explicit conversion exists (are
you missing a cast?)
Controller:
namespace RedPandaCourses.Controllers
{
public class SearchController : Controller
{
[HttpGet]
public ActionResult CourseSearchView()
{
var courses = new CourseSearchResultModel();
return View(courses);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CourseSearchView(CourseSearchResultModel vm)
{
var courses = new CourseSearchResultModel();
return View(courses);
}
2 Models:
namespace RedPandaCourses.Models
{
public class CourseSearchModel
{
public CourseSearchModel() { }
public string courseName { get; set; }
public int courseNumber { get; set; }
public string courseInstructor { get; set; }
public List<CourseSearchResultModel> results { get; set; }
}
}
and
namespace RedPandaCourses.Models
{
public class CourseSearchResultModel
{
public CourseSearchResultModel() { }
public decimal courseID { get; set; }
public string courseName { get; set; }
public string courseNumber { get; set; }
public string courseInstructorFirstName { get; set; }
public string courseInstructorLastName { get; set; }
public string courseInstructor { get; set; }
public string courseSchedule { get; set; }
}
}
It will send text box text to the database, search it from a select class, and return the results to the table using a foreach loop, however the foreach loop throws the error above.
View:
#Model RedPandaCourses.Models.CourseSearchResultModel;
#using RedPandaCourses.Models;
#{
ViewBag.Title = "CourseSearchView";
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<div class="container-fluid no-main-border">
<div class="row-fluid main-bg">
<div class="span12">
<h2 class="labelHide"> </h2>
<div class="row-fluid">
<div class="negMargin">
<div class="span9 inner-container">
<div class="streamlined-subhead">
<h1>Search Courses</h1>
</div>
#using (Html.BeginForm("CourseSearchView", "Search"))
{
var model = new CourseSearchModel();
<div id="the_id" class="question">
<div class="control-group" id="the_id_control-group">
<fieldset>
<div id="the_id_1_control-group" class="control-group">
<label class="control-label" for="courseName">Course Name: </label>
<div id="the_id_1_controls" class="controls">
#Html.TextBoxFor(m => model.courseName)
</div>
</div>
<div id="the_id_2_control-group" class="control-group">
<label class="control-label" for="courseNumber">Course Number: </label>
<div id="the_id_2_controls" class="controls">
#Html.TextBoxFor(m => model.courseNumber)
</div>
</div>
<div id="the_id_3_control-group" class="control-group">
<label class="control-label" for="instructor">Instructor: </label>
<div id="the_id_3_controls" class="controls">
#Html.TextBoxFor(m => model.courseInstructor)
</div>
</div>
<div class="previous-next-bar">
<button type="submit" class="btn btn-primary" id="courseSearch" onclick="location.href='#Url.Action("CourseSearchView","Search")'">Search</button>
</div>
</fieldset>
</div>
</div>
}
<div>
<h2>Search Results</h2>
<table id="example" class="table table-bordered table-striped table-hover dataTable width80">
<thead class="tableHeader" role="rowgroup">
<tr role="row">
<th class="sorting" role="columnheader">Course Title</th>
<th class="sorting" role="columnheader">Course Number</th>
<th class="sorting" role="columnheader">Instructor</th>
<th class="sorting" role="columnheader">Schedule</th>
</tr>
</thead>
<tbody>
#if (Model == null)
{
<tr>
<td colspan="4">no results</td>
</tr>
} else {
foreach (var item in Model)
{
Html.AntiForgeryToken();
<tr class="clickableRow" onclick="location.href='#Url.Action("InstructorCourseDetailView", "Instructor")'">
<td>#Html.Encode(item.courseName)</td>
<td>#Html.Encode(item.courseNumber)</td>
<td>#Html.Encode(item.courseInstructor)</td>
<td>#Html.Encode(item.courseSchedule)</td>
</tr>
}
}
<tr>
<td colspan="4">
<button class="btn btn-default" onclick="location.href='#Url.Action("AdminAddCourseView","Admin")'">Add Course</button>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<div class="previous-next-bar">
<button type="submit" class="btn btn-default" onclick="location.href='#Url.Action("AdminHome","Admin")'">Return</button>
</div>
</div>
</div>
</div>
</div>
</div>
I've looked everywhere including a bunch of questions on this site and cannot find anything that has helped me in this situation. I'm new to coding, this is the training application I'm doing for my new job and any help would be appreciated!
To start with, the form should sending a CourseSearchModel not a CourseSearchResultModel.
Second, in the action handling the post, you should query the database and put the result in the results property of the search model you received as an argument. Here is how to do it :
[HttpPost]
[ValidateAntiForgeryToken]
//Change the type of the object bound from the from
public ActionResult CourseSearchView(CourseSearchModel vm)
{
//Query the db and put the outcome in the results prop of the vm
vm.results = QueryTheDb();
//return the vm to the view
return View(vm);
}
Third, you give that object to the View method in the return line.
Fourth, change this
#Model RedPandaCourses.Models.CourseSearchResultModel;
with this
#Model RedPandaCourses.Models.CourseSearchModel;
in your view.

Categories