return to partial view as json? - c#

i had 2 views the "index" and "_Track". i need to return my datalist to "_Track"-this is partial view. can someone help me becoz i got this error. i need to return the data list into partial view.
Error
"for each statement cannot operate on variable type does not contain a public instance definition for getenumerator"
see the reference code below.
Parent model.
public class TrackingFormModel : BaseModel
{
public string TrackingNumber { get; set; }
public TrackingListModel TrackingList { get; set; }
}
Child model
public class TrackingListModel : BaseModel
{
public string Name { get; set; }
public string Departure { get; set; }
}
Index.cshtml
#using ChenvelMobile.Web.Models.Tracking
#model TrackingFormModel
#{
ViewBag.Title = "index";
Layout = null;
}
#using (Html.BeginForm("index", "tracking", FormMethod.Post))
{
#Html.HiddenFor(x => x.Id)
<div class="MainContainer">
<div class="row">
<div class="form-group">
<div class="col-md-12">
<h4>Track an Item</h4>
<p>Hint: Enter the correct tracking number (Example. AU0002004)</p>
<div class="input-group">
#Html.TextBoxFor(x => x.TrackingNumber, new { #class = "form-control", #id = "testSize", #placeholder = "Enter your box number..." })
<div class="input-group-btn">
<button class="btn btn-primary" type="submit" id="show">
<span class="glyphicon glyphicon-search btnSize" style="font-size: 20px"></span>
</button>
</div>
</div>
<br />
#Html.Partial("_Track", Model)
</div>
</div>
</div>
</div>
}
_Track.cshtml(Partial View)
#using ChenvelMobile.Web.Models.Tracking
#model TrackingListModel
#foreach (var item in Model)
{
<div>#item.Id</div>
<div>#item.Name</div>
<div>#item.Departure</div>
}
Controller
public JsonResult Index(TrackingFormModel model)
{
string date = String.Format("{0:MM/dd/yyyy}", DateTime.Now);
DateTime startdate = DateTime.Parse(date);
DateTime prevoiusdate = startdate.AddDays(-90);
var tracking = _cSI_DataService.Find(x => x.reciept_id == model.TrackingNumber).Where(x => Convert.ToDateTime(x.date_pl) > prevoiusdate).ToList();
var list = (from t in tracking
join d in _departureItemsTableService.GetAll() on t.box_id.Trim() equals d.BoxNo.Trim() into departitem from departitems in departitem.DefaultIfEmpty()
join dt in _departureTableService.GetAll() on departitems?.DepartureId equals dt.DepartureId into dep from depart in dep.DefaultIfEmpty()
select new TrackingListModel
{
Id = t.Id,
Name = t.firstname_s + " " + t.lastname_s,
Departure = depart?.DepartureDate ?? String.Empty,
});
return Json(new { data = list.ToList() }, JsonRequestBehavior.AllowGet);
}

Try passing the tracking list to your partial view. Currently you are passing a TrackingFormModel, not the expected TrackingListModel.
#Html.Partial("_Track", Model.TrackingList)

Related

Submit data with dynamically added partial view to the controller using ViewModels not working

I'm adding dynamically items to an Enquiry form. Used partial view to for adding/deleting the items but while submitting the main view the values are not bound. My question is how to do the same.
Have checked couple of similar questions here and here But could not find what's missing .
Using 2 ViewModels , for Main View ( Enquiry) and for partial view ( LineItems) and used BeginCollectionItem for dynamically adding items.
Code:
ViewModels
public class EnquiryVM
{
public int ID { get; set; }
[Required]
public string EnquiryNumber { get; set; }
public int ClientID { get; set; }
public IEnumerable<SelectListItem> Clients { get; set; }
public Client Client { get; set; }
public int ItemID { get; set; }
public List<EnquiryLineItem> LineItems { get; set; }
}
public class EnquiryLineItemVM
{
public int ID { get; set; }
[Required]
public string ItemDesc { get; set; }
public int Quantity { get; set; }
public int ManufacturerId { get; set; }
public IEnumerable<SelectListItem> ManufacturerList { get; set; }
}
Views :
Main:
#model ViewModel.EnquiryVM
#using (Html.BeginForm("Create", "Enquiries", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.EnquiryNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-3">
#Html.EditorFor(model => model.EnquiryNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EnquiryNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ClientID, "Client", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-3">
#Html.DropDownListFor(u => u.ClientID, (IEnumerable<SelectListItem>)Model.Clients, "--Select--")
#Html.ValidationMessageFor(model => model.ClientID, "", new { #class = "text-danger" })
</div>
</div>
<div id="LineItems">
// #using (Html.BeginForm()) // do we require again here since this will be like nested form? tested commenting still not working
// {
<div id="editorRowsLineitems">
#foreach (var item in Model.LineItems)
{
#Html.Partial("_CreateEnquiryItem", item)
}
</div>
#Html.ActionLink("Add Items", "CreateLineItem", null, new { id = "addItem", #class = "button" });
// }
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
$('#addItem').on('click', function () {
$.ajax({
url: '#Url.Action("CreateLineItem")',
cache: false,
success: function (html) {
$("#editorRowsLineitems").append(html);
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
}
});
return false;
});
$('#editorRowsLineitems').on('click', '.deleteRow', function () {
$(this).closest('.editorRow').remove();
});
$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));
});
</script>
}
partial view :
#model ViewModels.EnquiryLineItemVM
<div class="editorRow">
#using (Html.BeginCollectionItem("ItemList"))
{
<table class="table">
<tr>
<td>
#Html.EditorFor(model => model.ItemDesc)
</td>
<td>
#Html.EditorFor(model => model.Quantity)
</td>
<td>
#Html.DropDownListFor(model => model.ManufacturerId, Model.ManufacturerList, "--Please Select--")
</td>
<td>
Delete
</td>
</tr>
</table>
}
Controller :
public ActionResult Create()
{
var viewModel = GetAllCategories();
return View(viewModel);
}
private EnquiryVM GetAllCategories()
{
var model = new EnquiryVM();
var clients = db.Clients.ToList();
model.Clients = clients.Select(s => new SelectListItem
{
Value = s.ID.ToString(),
Text = s.Name
});
var LineItems = new List<EnquiryLineItem>();
model.LineItems = LineItems;
return model;
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create( EnquiryVM enquiryVM)
{
var enquiry = new Enquiry();
enquiry.EnquiryNumber = enquiryVM.EnquiryNumber;
enquiry.ClientID = enquiryVM.ClientID;
enquiry.EnquiryLineItems = enquiryVM.LineItems; //line items are null
if (ModelState.IsValid)
{
db.Enquiries.Add(enquiry);
enquiryVM.ID = enquiry.ID;
foreach (var item in enquiry.EnquiryLineItems)
{
item.EnquiryID = enquiryVM.ID;
db.EnquiryLineItems.Add(item);
}
db.SaveChanges();
return RedirectToAction("Index");
}
var viewModel = GetAllCategories();
return View(enquiryVM);
}
How shall I map the dynamically added row's values to the ViewModel ( EnquiryVM ) so that I can insert it into the DB.
Thanks for your patience and time.
The name of your collection property is LineItems, therefore your code to generate its controls needs to be
#using (Html.BeginCollectionItem("LineItems")) // not ..("ItemList")
{
....
}
so that it generates inputs with name="LineItems[xxxx].ItemDesc" etc, rather than your current use which generates name="ItemList[xxxx].ItemDesc" (where xxxx is the Guid)
As a side note, the code in your POST method will throw an exception if ModelState is invalid because you return the view and have not repopulated the IEnumerable<SelectListItem> Clients property. Refer The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable' for a detailed explanation.
In addition, the final 2 lines of your script to add items ($('form').data('validator', null); $.validator.unobtrusive.parse($('form')); should be removed (reparsing the validator is expensive and your doing it twice - once before you add the html (the 2 lines above) and once after you add the html

Display list of objects and set a value field for each input MVC

I have the following class defined as my ViewModel
public class CreateApplicationViewModel
{
public Step1ViewModel Step1 { get; set; }
public Step2StandAloneViewModel Step2StandAlone { get; set; }
public Step2ChildViewModel Step2Child { get; set; }
public Step3ViewModel Step3 { get; set; }
public Step4ViewModel Step4 { get; set; }
}
I'm trying to display items in the Step4ViewModel which consists of the following:
public class Step4ViewModel
{
public List<DataDetails> DataDetails = new List<DataDetails>();
}
public class DataDetails
{
public string GroupCode { get; set; }
public string GroupDesc { get; set; }
public decimal DetailSequence { get; set; }
public string DetailCode { get; set; }
public string DetailDesc { get; set; }
public string YesNoFlag { get; set; }
public string NumberFlag { get; set; }
public string ValueFlag { get; set; }
public string DateFlag { get; set; }
public string ListValuesFlag { get; set; }
public string CommentFlag { get; set; }
public string CalcRateFlag { get; set; }
public string ColumnSequence { get; set; }
public string TextFlag { get; set; }
public string CheckboxFlag { get; set; }
public string YesNoValue { get; set; }
public int NumberValue { get; set; }
public DateTime DateValue { get; set; }
public string ListValue { get; set; }
public string CommentValue { get; set; }
public string TextValue { get; set; }
public bool CheckboxValue { get; set; }
}
In my controller I populate the Step4ViewModel.DataDetails like so:
private Step4ViewModel GetCaseDataDetails(string caseType)
{
Step4ViewModel model = new Step4ViewModel();
List<DataDetails> data = new List<DataDetails>();
List<DataDetailsValues> values = new List<DataDetailsValues>();
var dataDetails = (from tb1 in db.DEFAULT_CASE_DATA_VW
join tb2 in db.CASE_DATA_DETAIL on tb1.CASE_DATA_GROUP_ID equals tb2.CASE_DATA_GROUP_ID
where tb1.BUS_CASE_CODE == caseType
orderby tb2.DETAIL_SEQUENCE
select new { tb1, tb2 });
foreach (var detail in dataDetails.ToList())
{
DataDetails i = new DataDetails();
DataDetailsValues j = new DataDetailsValues();
i.CalcRateFlag = detail.tb2.CALC_RATE_FLAG;
i.CheckboxFlag = detail.tb2.CHECKBOX_FLAG;
i.ColumnSequence = detail.tb2.COLUMN_SEQUENCE;
i.CommentFlag = detail.tb2.COMMENT_FLAG;
i.DateFlag = detail.tb2.DATE_FLAG;
i.DetailCode = detail.tb2.DETAIL_CODE;
i.DetailDesc = detail.tb2.DETAIL_DESC;
i.DetailSequence = detail.tb2.DETAIL_SEQUENCE;
i.GroupCode = detail.tb1.GROUP_CODE;
i.GroupDesc = detail.tb1.GROUP_DESC;
i.ListValuesFlag = detail.tb2.LIST_VALUES_FLAG;
i.NumberFlag = detail.tb2.NUMBER_FLAG;
i.TextFlag = detail.tb2.TEXT_FLAG;
i.ValueFlag = detail.tb2.VALUE_FLAG;
i.YesNoFlag = detail.tb2.YES_NO_FLAG;
data.Add(i);
}
model.DataDetails = data;
return model;
}
My thought process with the Step4ViewModel is that for every DataDetail I will display the DetailDesc as a label and then beside of it I will have an input for the NumberValue, YesOrNoValue, NumberValue, DateValue, ListValue, CommentValue, TextValue, or CheckboxValue depending on the control type and then post that data to server. I am able to successfully display each DataDetail.DetailDesc, but for each input, which also renders, the values I enter into the inputs never post back to the server. Here is what my view looks like:
#model Portal.Models.ViewModel.CreateApplicationViewModel
#{
ViewBag.Title = "Step 4/5";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using System.Linq
<h4>Case Data Details</h4>
#using (Html.BeginForm("Step4", "CreateApplication", FormMethod.Post, new { #class = "col-sm-12" }))
{
foreach (var group in Model.Step4.DataDetails.GroupBy(item => item.GroupDesc))
{
<div class="panel panel-primary">
<div class="panel-heading">#Html.Encode(group.Key)</div>
<div class="panel-body">
#for (var i = 0; i < group.Count(); i++)
{
<div class="form-group">
<div class="row">
<div class="col-xs-6">
<label class="form-label">#Model.Step4.DataDetails[i].DetailDesc</label>
</div>
<div class="col-xs-6">
#if (Model.Step4.DataDetails[i].TextFlag == "Y")
{
#Html.TextBoxFor(val => Model.Step4.DataDetails[i].TextValue, new { #class = "form-control" })
}
else if (Model.Step4.DataDetails[i].CheckboxFlag == "Y")
{
#Html.CheckBoxFor(val => Model.Step4.DataDetails[i].CheckboxValue, new { #class = "checkbox" })
}
</div>
</div>
</div>
}
</div>
</div>
}
<div class="col-sm-12">
<div class="row">
#Html.ActionLink("Cancel", "Welcome", "Home", null, new { #class = "btn btn-default" })
<button class="btn btn-default" onclick="history.go(-1);">Previous</button>
<button type="submit" class="btn btn-default">Next</button>
</div>
</div>
Controller to which post data
[HttpPost]
public ActionResult Step4(Step4ViewModel step4)
{
if (ModelState.IsValid)
{
CreateApplicationViewModel model = (CreateApplicationViewModel)Session["case"];
// model.Step4 = step4;
Session["case"] = model;
return View();
}
return View();
}
I was thinking this could be due the grouping, which I do to separate each group into a separate HTML panel element, but my inputs are rendering with the index number in the name. Any help or suggestions on a better way to accomplish this would be greatly appreciated. Cheers!
UPDATE
Here is my updated post controller and view:
#model Portal.Models.ViewModel.CreateApplicationViewModel
#{
ViewBag.Title = "Step 4/5";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using System.Linq
<h4>Case Data Details</h4>
#using (Html.BeginForm("Step4", "CreateApplication", FormMethod.Post, new { #class = "col-sm-12" }))
{
int index = 0;
foreach (var group in Model.Step4.DataDetails.GroupBy(item => item.GroupDesc))
{
<div class="panel panel-primary">
<div class="panel-heading">#Html.Encode(group.Key)</div>
<div class="panel-body">
<input type="hidden" name="Step4.DataDetails.Index" value="#index" />
#for (var i = 0; i < group.Count(); i++)
{
<div class="form-group">
<div class="row">
<div class="col-xs-6">
<label class="form-label">#Model.Step4.DataDetails[i].DetailDesc</label>
</div>
<div class="col-xs-6">
#if (Model.Step4.DataDetails[i].TextFlag == "Y")
{
#Html.TextBoxFor(val => val.Step4.DataDetails[i].TextValue, new { #class = "form-control" })
}
else if (Model.Step4.DataDetails[i].CheckboxFlag == "Y")
{
#Html.CheckBoxFor(val => val.Step4.DataDetails[i].CheckboxValue, new { #class = "checkbox" })
}
</div>
</div>
</div>
}
</div>
</div>
index++;
}
<div class="col-sm-12">
<div class="row">
#Html.ActionLink("Cancel", "Welcome", "Home", null, new { #class = "btn btn-default" })
<button class="btn btn-default" onclick="history.go(-1);">Previous</button>
<button type="submit" class="btn btn-default">Next</button>
</div>
</div>
}
[HttpPost]
public ActionResult Step4(CreateApplicationViewModel step4)
{
if (ModelState.IsValid)
{
CreateApplicationViewModel model = (CreateApplicationViewModel)Session["case"];
// model.Step4 = step4;
Session["case"] = model;
return View();
}
return View();
}
UPDATE 2
I am able to get the form input if I pass a FormCollection to the HttpPost controller. Any ideas as to why I can get these values as a FormCollection but not as the model?
You are posting list of complex objects. But MVC DefaultModelBinder can’t able to bind to your DataDetails object because Index must be in sequence when posting the form with list of complex objects. In your case due to nested for loop, this sequence is broken. So what you can do is take one separate variable and initialize with default 0 value like this - I have tried to modify your code.
#using (Html.BeginForm("Step4", "CreateApplication", FormMethod.Post, new { #class = "col-sm-12" }))
{
int index = 0;
foreach (var group in Model.Step4.DataDetails.GroupBy(item => item.GroupDesc))
{
<div class="panel panel-primary">
<div class="panel-heading">#Html.Encode(group.Key)</div>
<div class="panel-body">
<input type="hidden" name="Step4.DataDetails.Index" value="#index" />
#for (var i = 0; i < group.Count(); i++)
{
<div class="form-group">
<div class="row">
<div class="col-xs-6">
<label class="form-label">#Model.Step4.DataDetails[i].DetailDesc</label>
</div>
<div class="col-xs-6">
#if (Model.Step4.DataDetails[i].TextFlag == "Y")
{
#Html.TextBoxFor(val => val.Step4.DataDetails[i].TextValue, new { #class = "form-control" })
}
else if (Model.Step4.DataDetails[i].CheckboxFlag == "Y")
{
#Html.CheckBoxFor(val => val.Step4.DataDetails[i].CheckboxValue, new { #class = "checkbox" })
}
</div>
</div>
</div>
}
</div>
</div>
index++;
}
<div class="col-sm-12">
<div class="row">
#Html.ActionLink("Cancel", "Welcome", "Home", null, new { #class = "btn btn-default" })
<button class="btn btn-default" onclick="history.go(-1);">Previous</button>
<button type="submit" class="btn btn-default">Next</button>
</div>
</div>
}
Look at the hidden field i have added in the view. That do the trick to post your data even with the broken sequences. Hope this help you.
I was able to get the model back to the controller by taking the idea of using an index integer and incrementing it from the answer above and implementing the idea in a different way in my view:
#model Portal.Models.ViewModel.CreateApplicationViewModel
#{
ViewBag.Title = "Step 4/5";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using System.Linq
<h4>Case Data Details</h4>
#using (Html.BeginForm("Step4", "CreateApplication", FormMethod.Post, new { #class = "col-sm-12" }))
{
int index = 0;
foreach (var group in Model.Step4.DataDetails.GroupBy(item => item.GroupDesc))
{
<div class="panel panel-primary">
<div class="panel-heading">#Html.Encode(group.Key)</div>
<div class="panel-body">
#for (var i = 0; i < group.Count(); i++)
{
<div class="form-group">
<div class="row">
<div class="col-xs-6">
<label class="form-label">#Model.Step4.DataDetails[i].DetailDesc</label>
</div>
<div class="col-xs-6">
#Html.TextBoxFor(val => val.Step4.DataDetails[index].TextValue)
#Html.HiddenFor(val => val.Step4.DataDetails[index].GroupCode)
</div>
</div>
</div>
index++;
}
</div>
</div>
}
<div class="col-sm-12">
<div class="row">
#Html.ActionLink("Cancel", "Welcome", "Home", null, new { #class = "btn btn-default" })
<button class="btn btn-default" onclick="history.go(-1);">Previous</button>
<button type="submit" class="btn btn-default">Next</button>
</div>
</div>
}
The above code in the view gives me the proper index of every element and allows me to post

Implementing bound dropdown list in MVC5 - Post action returns null values

I appear to be having some problems with dropdown list populating and binding in MVC. The simple example I have has a List of Movies with a Genre item that is populated with a drop down.
I pass across a Select List with the items to populate the drop down but appear to be running into problems when the post action is happening.
The problems appear to be :
The ViewModel being returned appears to return the GenreList as null on the Post action.
The Genre does not appear to be set so that after the edit -the dropdown list is populated correctly.
I cannot seem to find a good answer for this and have been trying quite a few examples but seem to be going round in circles. Would like to try and get this most basic of dropdown list edit example working so I can see how this should be implemented.
Model Classes
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Test.Models
{
public class Genre
{
[Key]
public int Id { get; set; }
public string Description { get; set; }
}
public class Movie
{
[Key]
public int MovieID { get; set; }
public string Name { get; set; }
public Genre MovieGenre { get; set; }
}
public class MovieViewModel
{
public Movie MovieItem { get; set; }
public SelectList GenreList{ get; set; }
}
}
Controller Code
namespace Test.Controllers
{
public class MoviesController : Controller
{
private DataContext _dc = new DataContext();
// GET: Movies
public ActionResult Index()
{
var x = from m in _dc.Movies
select m;
return View(x.ToList());
}
// GET: Movies/Edit/5
public ActionResult Edit(int id)
{
var x = from m in _dc.Movies
where m.MovieID == id
select m;
var l = from m in _dc.Genres
select m;
var y = new MovieViewModel
{
GenreList = new SelectList(l.ToList(), "ID", "Description"),
MovieItem = x.FirstOrDefault()
};
return View(y);
}
// POST: Movies/Edit/5
[HttpPost]
public ActionResult Edit(int id, MovieViewModel m)
{
// PROBLEM: GenreList in model is now not populate for return
if (ModelState.IsValid)
{
var movie = _dc.Movies.Find(id);
movie.Name = m.MovieItem.Name;
movie.MovieGenre = m.MovieItem.MovieGenre;
// PROBLEM: The MovieGenre does not appear to be saved correctly
// when you make the edit and go back to that record after saving
// the dropdown is not populated.
_dc.SaveChanges();
return RedirectToAction("Index", "Movies");
}
return View(m);
}
}
}
Razor View Code
#model Test.Models.MovieViewModel
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Movie</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.MovieItem.MovieID)
<div class="form-group">
#Html.LabelFor(model => model.MovieItem.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MovieItem.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MovieItem.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div>
#Html.LabelFor(m => m.GenreList, "Genre:")
#Html.DropDownListFor(m => m.MovieItem.MovieGenre.Id, (IEnumerable<SelectListItem>) Model.GenreList)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>

Ajax.BeginForm with Dropdown + Server Side Validation

I am trying to build an Ajax.BeginForm (that has a dropdown) which uses server side validation that checks the model's annotations. I am having trouble getting the dropdown to work properly. Originally I populated the dropdown using the viewbag as such:
view:
#Html.DropDownList("CheckIn_Location", ViewBag.CageLocationList as IEnumerable<SelectListItem>, "(Select one)", new { #class = "form-control" })
controller:
public void GetCageLocations()
{
IEnumerable<SelectListItem> selectList =
from c in db.Locations
select new SelectListItem
{
Text = c.LocationName,
Value = c.Id.ToString()
};
ViewBag.CageLocationList = selectList;
}
But that didn't seem to play friendly with server side validation so I am tried reworking my model/view/controllers as such:
Here is my Model:
public class CheckInViewModel
{
public int CheckIn_Id { get; set; }
[Required(ErrorMessage = "Location Required.")]
public IEnumerable<SelectListItem> CheckIn_Location { get; set; }
[Required(ErrorMessage = "Quantity Required.")]
[Range(1, 100, ErrorMessage = "Quantity must be between 1 and 100000")]
public int CheckIn_Quantity { get; set; }
public string CheckIn_Comment { get; set; }
}
Here is my Controller:
[HttpPost]
public ActionResult CheckIn(CheckInViewModel model)
{
if (ModelState.IsValid)
{
var New_Transaction = new Transaction
{
Id = model.CheckIn_Id,
Quantity = model.CheckIn_Quantity,
LocationId = Convert.ToInt32(model.CheckIn_Location),
TransactionDate = DateTime.Now,
TransactionComments = model.CheckIn_Comment.Replace("\r\n", " ")
};
unitOfWork.TransactionRepository.Insert(New_Transaction);
unitOfWork.Save();
return PartialView("CheckIn", model);
}
return PartialView("CheckIn", model);
}
Here is my PartialView called CheckIn.cshtml
#model ViewModels.CheckInViewModel
<!-- Modal -->
<div class="modal fade" id="CheckInModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h1 class="modal-title" id="CheckInModalLabel">Check In</h1>
</div>
<div class="modal-body">
#using (Ajax.BeginForm("CheckIn", "Cage", null, new AjaxOptions { HttpMethod = "POST", OnSuccess = "success", OnFailure = "failure"}, new { #id = "CheckInForm", #class = "form-horizontal" }))
{
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.CheckIn_Id, new { #class = "form-control" })
<div class="form-group">
<label for="CheckIn_Location" class="col-sm-4 control-label">Location</label>
<div class="col-sm-8">
#Html.DropDownListFor(x => x.CheckIn_Location, Model.CheckIn_Location, "Select One")
#Html.ValidationMessageFor(model => model.CheckIn_Location)
</div>
</div>
<div class="form-group">
<label for="CheckIn_Quantity" class="col-sm-4 control-label">Quantity</label>
<div class="col-sm-8">
#Html.TextBoxFor(model => model.CheckIn_Quantity, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CheckIn_Quantity)
</div>
</div>
<div class="form-group">
<label for="CheckIn_Comment" class="col-sm-4 control-label">Comment</label>
<div class="col-sm-8">
#Html.TextAreaFor(model => model.CheckIn_Comment, new { #class = "form-control" })
</div>
</div>
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="SubmitCheckInForm()">Check In</button>
</div>
</div>
</div>
</div>
here is the JS function that fire the submit:
function SubmitCheckInForm() {
$('#CheckInForm').submit();
}
Can someone show me how to:
populate the dropdown with (value/text) using the model as the binding agent (not the viewbag as I previously did it)
return the selected option to the controller and insert it into the transaction table's location element (which is an int)
properly hook this all up so the server side annotations work and return messages when something is incorrect in the form.
Thanks in Advance!
If I have understood you correctly, there is more than one way to do this. For instance, you could have two properties in your model to manage the Dropdown control.
1- CheckIn_Location_Selected. To store the value selected by the user
2- CheckIn_Location_List. To fill the DropdownList.
This could be your model.
public class CheckInViewModel
{
[Required(ErrorMessage = "Location Required.")]
public int CheckIn_Location_Selected { get; set; }
public IEnumerable<SelectListItem> CheckIn_Location_List { get; set; }
//Rest of the properties...
}
So now in your GET action you could have something like this:
[HttpGet]
public ActionResult CheckIn()
{
var model = new CheckInViewModel
{
CheckIn_Location_List = repository.GetCageLocations().Select(
location => new SelectListItem
{
Value = location.Id.ToString(),
Text = location.LocationName
})
};
return View(model);
}
And in your view:
#Html.DropDownListFor(x => x.CheckIn_Location_Selected, Model.CheckIn_Location_List, "Select One")
We need to change a bit your POST action.
[HttpPost]
public ActionResult CheckIn(CheckInViewModel model)
{
if (!ModelState.IsValid)
{
// This is necessary because we are sending the model back to the view.
// You could cache this info and do not take it from the DB again.
model.CheckIn_Location_List = repository.GetCageLocations().Select(
location => new SelectListItem
{
Value = location.Id.ToString(),
Text = location.LocationName
});
return PartialView("CheckIn", model);
}
var New_Transaction = new Transaction
{
Id = model.CheckIn_Id,
Quantity = model.CheckIn_Quantity,
LocationId = Convert.ToInt32(model.CheckIn_Location_Selected),
TransactionDate = DateTime.Now,
TransactionComments = model.CheckIn_Comment.Replace("\r\n", " ")
};
unitOfWork.TransactionRepository.Insert(New_Transaction);
unitOfWork.Save();
return PartialView("CheckIn", model);
}

How to have List Objects retained in the model on HttpPost?

I have a Model that contains a List of a custom type.
I want the data from this type to be passed back in when a model is submitted as a HttpPost call the the controller.
However, it does not seem to do what I want. I've got where I am so far by following Passing IEnumerable or list Model to Controller using HttpPost but I'm having a problem.
My controller method:
[HttpPost]
public ActionResult UpdateStock(int id, ProductModel model)
{
return View("UpdateStock", model);
}
Now, the View is like this (trimmed):
#using (Html.BeginForm())
{
<div>
<p>
<input type="submit" value="Save" />
</p>
#Html.HiddenFor(m => m.ProductNo)
<div class = "title">
#Html.LabelFor(m => m.ProductName)
#Html.EditorFor(m => m.ProductName)
</div>
#for ( int i = 0; i < Model.Stock.Count; i++ )
{
var item = Model.Stock[i];
<div class="editor-field">
<input type="text" name="Model.Stock[#i].Key"
value="#item.Key" />
</div>
<div class="editor-field">
<input type="text" name="Model.Stock[#i].Value"
value="#item.Value" />
</div>
}
}
My problem is, that it seems the #Html.EditorFor() and <input type=.../> tags don't seem to play well with each other. If I have it like above, then the ProductNo and other properties using #Html methods won't be passed through to the model.
Any advice much appreciated.
I would simply use editor templates:
Model:
public class ProductModel
{
public string ProductNo { get; set; }
public string ProductName { get; set; }
public IEnumerable<Stock> Stocks { get; set; }
}
public class Stock
{
public string Key { get; set; }
public string Value { get; set; }
}
Controller:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new ProductModel
{
ProductNo = "123",
ProductName = "p name",
Stocks = new[]
{
new Stock { Key = "key1", Value = "value1" },
new Stock { Key = "key2", Value = "value2" },
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(ProductModel model)
{
...
}
}
View:
#model ProductModel
#using (Html.BeginForm())
{
<p>
<input type="submit" value="Save" />
</p>
#Html.HiddenFor(m => m.ProductNo)
<div class = "title">
#Html.LabelFor(m => m.ProductName)
#Html.EditorFor(m => m.ProductName)
</div>
#Html.EditorFor(x => x.Stocks)
}
and then you define a custom editor template for the Stock type (~/Views/Shared/EditorTemplates/Stock.cshtml):
#model Stock
<div class="editor-field">
#Html.EditorFor(x => x.Key)
</div>
<div class="editor-field">
#Html.EditorFor(x => x.Value)
</div>

Categories