Using MultiSelect List in MVC 3 - asp.net-mvc-3

Right now I am working on a multiselect list in MVC 3. I was able to get over a big hurdle earlier today which was populating the dropdown list with version data from the database. The problem is that it is showing every item that is in the table column VERSION. I know that this is a simple fix but I can't seem to figure it out.... I was thinking that all I have to do is add an if statement with an enumerator that says something like the following psudocode.
while VERSION <> null
if version = version
then don't display version
end while
At the moment it is displaying all 387 rows of VERSION and all I need it to display is the first instance of a version so if the version was 1.5 it only displays the first one so I can grab it for another record, I hope this makes sense. I have included my controller class and my edit class below. Please let me know if you need any of my other classes for diagnosis. Thanks for your HELP!
EDIT 04/11/12
It seems that I need to clarify my request some so here is my attempt at that for you guys.
What I need help with is fixing the selectList code so it only returns the first instance of a VERSION. At the moment when I click on the drop down it is filled with every row from the column VERSION which means that I have 385 instances in the drop down saying version 1.2 and two instances of 1.3. What I would like it to do is to fill the drop down with just two instances of the version 1.2 and 1.3. PLEASE HELP I would offer a bounty if I had more points but I am new so all I can say is if you help at all I promise to upvote! Thanks for your help!
PACONTROLLER.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Web.UI.WebControls;
using System.Web;
using System.Web.Mvc;
using DBFirstMVC.Models;
using System.Data;
using PagedList;
using PagedList.Mvc;
using DBFirstMVC.Controllers;
using System.IO;
using DBFirstMVC;
using System.Web.UI;
namespace DBFirstMVC.Controllers
{
public class PaController : Controller
{
PaEntities db = new PaEntities();
// Index Method
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder; //ViewBag property provides the view with the current sort order
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "PA desc" : ""; // Calls the sortOrder switch/case PA desc or default
ViewBag.MPSortParm = sortOrder == "MP" ? "MP desc" : "MP asc"; // Calls the sortOrder switch/case MP desc or MP asc
ViewBag.IASortParm = sortOrder == "IA" ? "IA desc" : "IA asc"; // Calls the sortOrder switch/case IA desc or IA asc
ViewBag.VersionSortParm = sortOrder == "VERSION" ? "Version desc" : "Version asc"; // Calls the sortOrder switch/case Version desc or Version asc
ViewBag.IAMP_PKSortParm = sortOrder == "IAMP_PK" ? "IAMP_PK desc" : "IAMP_PK asc"; // Calls the sortOrder switch/case IAMP_PK desc or IAMP_PK asc
if (Request.HttpMethod == "GET")
{
searchString = currentFilter; //sets the currentFilter equal to Searchstring
}
else
{
page = 1; // defaults to page 1
}
ViewBag.CurrentFilter = searchString; // Provides the view with the current filter string
var IAMP = from p in db.iamp_mapping select p;
if (!String.IsNullOrEmpty(searchString))
{
IAMP = IAMP.Where(p => p.PA.ToUpper().Contains(searchString.ToUpper())); //selects only records that contains the search string
}
switch (sortOrder) // switch case changes based on desired sort
{
case "Pa desc":
IAMP = IAMP.OrderByDescending(p => p.PA);
break;
case "MP desc":
IAMP = IAMP.OrderByDescending(p =>p.MAJOR_PROGRAM);
break;
case "MP asc":
IAMP = IAMP.OrderBy(p =>p.MAJOR_PROGRAM);
break;
case "IA desc":
IAMP = IAMP.OrderByDescending(p => p.INVESTMENT_AREA);
break;
case "IA asc":
IAMP = IAMP.OrderBy(p => p.INVESTMENT_AREA);
break;
case "Version asc":
IAMP = IAMP.OrderBy(p => p.VERSION);
break;
case "Version desc":
IAMP = IAMP.OrderByDescending(p => p.VERSION);
break;
case "IAMP_PK asc":
IAMP = IAMP.OrderBy(p => p.IAMP_PK);
break;
case "IAMP_PK desc":
IAMP = IAMP.OrderByDescending(p => p.IAMP_PK);
break;
default:
IAMP = IAMP.OrderBy(p => p.PA);
break;
}
int pageSize = 15; // number of records shown
int pageNumber = (page ?? 1); // start page number
return View(IAMP.ToPagedList(pageNumber, pageSize)); // uses pagedList method to return correct page values
}
// Instantiates create method
// GET: /Pa/Create
public ActionResult Create()
{
SetVersionViewBag();
return View();
}
// Create method adds records to Database and saves changes
// POST: /Pa/Create
[HttpPost]
public ActionResult Create(iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
db.iamp_mapping.Add(IAMP);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
ViewBag.VERSION = new MultiSelectList(db.iamp_mapping, "VERSION", "VERSION", IAMP.VERSION);
return View(IAMP);
}
}
// Instantiates Edit Method
// GET: /Pa/Edit/5
public ActionResult Edit(string id)
{
using (var db = new PaEntities())
{
iamp_mapping IAMP = db.iamp_mapping.Find(id);
SetVersionViewBag(IAMP.VERSION);
return View(IAMP);
}
}
// Edit method modifies existing records and saves changes
// POST: /Pa/Edit/5
[HttpPost]
public ActionResult Edit(string id, iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
db.Entry(IAMP).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("");
}
}
catch
{
SetVersionViewBag(IAMP.VERSION);
return View(IAMP);
}
}
// Instantiates delete method
// GET: /Pa/Delete/5
public ActionResult Delete(string id)
{
using (var db = new PaEntities())
{
return View(db.iamp_mapping.Find(id));
}
}
// Delete method renames primary key and then removes record from database
// POST: /Pa/Delete/5
[HttpPost]
public ActionResult Delete(string id, iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
var vIAMP = db.iamp_mapping.Find(id);
db.Entry(vIAMP).State = EntityState.Deleted;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (Exception e)
{
throw (e);
//return View();
}
}
public ActionResult IAMP_Mapping(iamp_mapping IAMP)
{
var iamp_mapping = db.iamp_mapping as IEnumerable<iamp_mapping>;
var grid = new GridView
{
DataSource = from p in iamp_mapping
select new
{
PA = p.PA,
MP = p.MAJOR_PROGRAM,
IA = p.INVESTMENT_AREA,
VERSION = p.VERSION,
IAMP_PK = p.IAMP_PK
}
};
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-dispostion", "inline; filename= Excel.xls");
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
return View("Index");
}
public ActionResult SelectVersion() {
List<SelectListItem> versions = new List<SelectListItem>();
versions.Add(new SelectListItem { Text = "Action", Value = "0" });
versions.Add(new SelectListItem { Text = "Drama", Value = "1" });
versions.Add(new SelectListItem { Text = "Comedy", Value = "2", Selected = true });
versions.Add(new SelectListItem { Text = "Science Fiction", Value = "3" });
ViewBag.VersionType = versions;
return View();
}
public ViewResult VersionChosen(string VersionType)
{
ViewBag.messageString = VersionType;
return View("Information");
}
public enum eVersionCategories { Action, Drama, Comedy, Science_Fiction };
private void SetViewBagVersionType(eVersionCategories selectedVersion)
{
IEnumerable<eVersionCategories> values =
Enum.GetValues(typeof(eVersionCategories))
.Cast<eVersionCategories>();
IEnumerable<SelectListItem> versions =
from value in values
select new SelectListItem
{
Text = value.ToString(),
Value = value.ToString(),
Selected = value == selectedVersion,
};
ViewBag.VersionType = versions;
}
public ActionResult SelectVersionEnum()
{
SetViewBagVersionType(eVersionCategories.Drama);
return View("SelectVersion");
}
public ActionResult SelectVersionEnumPost()
{
SetViewBagVersionType(eVersionCategories.Comedy);
return View();
}
[HttpPost]
public ActionResult SelectVersionEnumPost(eVersionCategories VersionType)
{
ViewBag.messageString = VersionType.ToString() + " val = " + (int)VersionType;
return View("Information");
}
private void SetVersionViewBag(string VERSION = null)
{
if (VERSION == null)
ViewBag.VERSION = new MultiSelectList(db.iamp_mapping, "VERSION", "VERSION");
else
ViewBag.VERSION = new MultiSelectList(db.iamp_mapping.ToArray(), "VERSION", "VERSION", VERSION);
}
}
}
EDIT.CSHTML
#model DBFirstMVC.Models.iamp_mapping
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>iamp_mapping</legend>
<div class="editor-label">
#Html.LabelFor(model => model.PA)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PA)
#Html.ValidationMessageFor(model => model.PA)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MAJOR_PROGRAM)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MAJOR_PROGRAM)
#Html.ValidationMessageFor(model => model.MAJOR_PROGRAM)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.INVESTMENT_AREA)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.INVESTMENT_AREA)
#Html.ValidationMessageFor(model => model.INVESTMENT_AREA)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.VERSION)
</div>
<div class="editor-field">
#Html.DropDownList("Version", ViewBag.Version as MultiSelectList)
#Html.ValidationMessageFor(model => model.VERSION)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.IAMP_PK)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.IAMP_PK)
#Html.ValidationMessageFor(model => model.IAMP_PK)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "")
</div>

SELECT DISTINCT
Version
FROM YourTable
This will give you a distinct list of versions. It's not clear what help you want with your controller and views.
Edit:
Or if you want to use linq in your controller (assuming that Version is a property of db.iamp_mapping)
db.iamp_mapping.Select(x => new iamp_mapping{Version = x.Version}).Distinct().ToList();

Related

has error after add pagedList.Mvc package to my project

I wanted to add page number with a pagedList.MVC package into my razor view page so I added package and then it's my Controller:
public ViewResult Index(string sortOrder, string currentFilter, string searchPathId, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.IdPercorsoSortParm = String.IsNullOrEmpty(sortOrder) ? "IdPercorso_desc" : "";
if (searchPathId != null)
{
page = 1;
}
else
{
searchPathId = currentFilter;
}
ViewBag.CurrentFilter = searchPathId;
var listPercorsiModel = from listObj in _context.PercorsiModel
orderby listObj.IdPercorso
select listObj;
if (!String.IsNullOrEmpty(searchPathId))
{
//listPercorsiModel = listPercorsiModel.Where(s => s.IdPercorso == (System.Convert.ToInt32(searchPathId))).ToList();
}
switch (sortOrder)
{
case "IdPercorso_desc":
listPercorsiModel = listPercorsiModel.OrderByDescending(s => s.IdPercorso);
break;
//case "Date":
// students = students.OrderBy(s => s.EnrollmentDate);
// break;
//case "date_desc":
// students = students.OrderByDescending(s => s.EnrollmentDate);
// break;
}
int pageSize = 3;
int pageNumber = (page ?? 1);
//return View(students.ToPagedList(pageNumber, pageSize));
return View(listPercorsiModel.ToPagedList(pageNumber, pageSize));
}
and then in my view after add this code i had error:
#Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
my error:
ok, want to inform that because I used .net core application had a problem and I found another package for paging number and its working perfect:
x.pagedlist.mvc.core

how can i get dropdownlist id in controller when we select an item using mvc4

I have dropdownlst which i have filled from database. Now i need to get the selected value in Controller do some manipulation. But null data will get. Code which i have tried.
##View##
#using (Html.BeginForm()) {
#Html.DropDownList("SupplierId", ViewBag.PurSupName as SelectList, new {#class = "form-control",style = "width: 200px;",id="supId"})
}
## Controller ##
public ActionResult ItemPurchased()
{
POS_DBEntities2 db = new POS_DBEntities2();
var query = from i in db.TBL_Account
where i.Type == "supplier"
select i;
ViewBag.PurSupName = new SelectList(query, "AccountId", "AccountName");
return PartialView("ItemPurchased", new List<PurchasedItem>());
}
##Controller##
public ActionResult GetPurchasedItem()
{
var optionsValue = this.Request.Form.Get("SupplierId");
return View();
}
You can try with below changes.
#using (Html.BeginForm("GetPurchasedItem","YourController")) {
#Html.DropDownList("SupplierId", ViewBag.PurSupName as SelectList, new {#class = "form-control",style = "width: 200px;",id="supId"})
<input type="submit" value="OK" />
}
Controller will be
[HttpPost]
public ActionResult GetPurchasedItem(string SupplierId)
{
var optionsValue = SupplierId;
//..............
return View();
}
It should work normally..

the paging of Grid.MVC not work

Im using Grid.MVC in my MVC web application
When test it in a blank page with index controller it works successfully with pagination and filtration.
The Problem accrue when i put it in my project
the steps that i do that i make ajax request (because i don't need to reload the page) to method and return a partial view that contains the result of the search by the Grid.Mvc the result and number of pages return successfully but when i press to next page or filter it doesn't work.
Code:
View:
#using (Ajax.BeginForm("Search", "Home",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "SearchResult"
})){
#Html.DropDownList("Province", "Province")
#Html.DropDownList("Cities", "Cities")
<span>price from :</span> <input type="text" name="Pricefrom" />
<span>to :</span> <input type="text" name="Priceto" />
<input type="submit" value="Search" /> }
Search Controller :
[HttpPost]
public ActionResult Search(int? page , int Province = 0, int Cities = 0, int Pricefrom = 0, int Priceto = 0)
{
var ads = db.Ad.Where(a => (Cities == 0 || a.CityId == Cities) &&
(Province == 0 || a.Cities.ProvinceId == Province)&&
(Pricefrom == 0 || a.Price >= Pricefrom)&&
(Priceto == 0 || a.Price <= Priceto)).OrderBy(a => a.AdDate).ToList();
return PartialView("_Search", ads);
}
PartialView:
#using GridMvc.Html
#model IEnumerable<Semsark.Areas.Backend.Models.Ad>
<div>
#Html.Grid(Model).Columns(columns =>
{
columns.Add(c => c.Id).Titled("ID");
columns.Add(c => c.AdTitle).Titled("title");
columns.Add(c => c.AdBody).Titled("body");
}).WithPaging(2).Sortable(true)
</div>
scripts and styles in the View index.cshtml :
<head>
<meta name="viewport" content="width=device-width" />
<link href="#Url.Content("~/Content/Gridmvc.css")" rel="stylesheet" />
<script src="#Url.Content("~/Scripts/gridmvc.min.js")"></script>
<script src="~/Scripts/gridmvc.lang.ru.js"></script>
<title>Index</title>
Thanks in advance for any help,
#*Webgrid using Paging in mvc 4.
View Page **.cshtml** *#
#model MvcPopup.Models.PagedEmployeeModel
#{
//ViewBag.Title = "SearchEmployee";
Layout = null;
}
#{
WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);
grid.Bind(Model.Employee,
autoSortAndPage: false,
rowCount: Model.TotalRows
);
}
#grid.GetHtml(
fillEmptyRows: false,
alternatingRowStyle: "alternate-row",
headerStyle: "grid-header",
footerStyle: "grid-footer",
mode: WebGridPagerModes.All,
firstText: "<< First",
previousText: "< Prev",
nextText: "Next >",
lastText: "Last >>",
columns: new[] {
grid.Column("Name",
header: "Name",
format: #<text>
#Html.ActionLink((string)item.Name, "ViewEmployeeDetail", new { id = item.id }, new { #class = "viewDialog" })</text>
),
grid.Column("Department"),
grid.Column("City"),
grid.Column("State"),
grid.Column("Country",
header: "Country"
),
grid.Column("Mobile"),
grid.Column("",
header: "Actions",
format: #<text>
#Html.ActionLink("Edit", "EditEmployee", new { id = item.id }, new { #class = "editDialog" })
|
#Html.ActionLink("Delete", "Delete", new { id = item.id }, new { #class = "confirmDialog"})
</text>
)
})
#*-----------------------------------
Model folder under modelservices.cs file
=================================*#
public IEnumerable<Employee> GetEmployeePage(int pageNumber, int pageSize, string searchCriteria)
{
if (pageNumber < 1)
pageNumber = 1;
return db.Employees
.OrderBy(m =>m.Name)
.Skip((pageNumber - 1) * pageSize)
.Take(pageSize)
.ToList();
}
public int CountAllEmployee()
{
return db.Employees.Count();
}
public class PagedEmployeeModel
{
public int TotalRows { get; set; }
public IEnumerable<Employee> Employee { get; set; }
public int PageSize { get; set; }
}
#*Controller folder under create file like employeecontroller.cs *#
using MvcPopup.Models;
using System.Globalization;
using System.Text;
namespace MvcPopup.Controllers
{
public class EmployeeController : Controller
{
//
// GET: /Employee/
ModelServices mobjModel = new ModelServices();
public ActionResult Index()
{
return View();
}
public ActionResult SearchEmployee(int page = 1, string sort = "name", string sortDir = "ASC")
{
const int pageSize = 5;
var totalRows = mobjModel.CountAllEmployee();
sortDir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? sortDir : "asc";
var validColumns = new[] { "id", "name", "department", "country" };
if (!validColumns.Any(c => c.Equals(sort, StringComparison.CurrentCultureIgnoreCase)))
sort = "id";
var employee = mobjModel.GetEmployeePage(page, pageSize, "it." + sort + " " + sortDir);
var data = new PagedEmployeeModel()
{
TotalRows = totalRows,
PageSize = pageSize,
Employee = employee
};
return View(data);
}
------------------------
Have you tried to pass through an IQueryable list instead of an IEnumerable? According to the documentation, Gridmvc.Html requires an IQueryable for paging. There are some subtle differences between IQueryable and IEnumerable that might make a difference here.
These scripts are needed for paging:
"~/Scripts/GridMvc/URI.js"
"~/Scripts/GridMvc/gridmvc.min.js"
"~/Scripts/GridMvc/gridmvc-ext.js"

MVC 3 Model binding and No parameterless constructor defined for this object

I created a view that was working wonderfully until I added some JQuery to support cascading drop downs. I believe in doing that, I broke the binding between the view and the model. I'm getting the error "No parameterless constructor defined for this object." when the form is submitted. The obvious solution would be to add a parameterless constructor, but I'm assuming that the postmodel will be null? Code Snippets below.
Thanks in Advance for your help.
View:
<script type="text/javascript">
$(document).ready(function () {
$("#ddlCategories").change(function () {
var iCategoryId = $(this).val();
$.getJSON(
"#Url.Content("~/Remote/SubCategoriesByCateogry")",
{ id: iCategoryId },
function (data) {
var select = ResetAndReturnSubCategoryDDL();
$.each(data, function (index, itemData) {
select.append($('<option/>', { value: itemData.Value, text: itemData.Text }));
});
});
});
function ResetAndReturnSubCategoryDDL() {
var select = $('#ddlSubCategory');
select.empty();
select.append($('<option/>', { value: '', text: "--Select SubCategory--" }));
return select;
}
});
...
<div class="editor-field">
#Html.DropDownList("iCategoryID", Model.Categories,"--Select Category--", new Dictionary<string,object>{ {"class","dropdowns"},{"id","ddlCategories"}})
#Html.ValidationMessage("iCategoryID")
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SubCategories, "SubCategory")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.SubCategories, new SelectList(Enumerable.Empty<SelectListItem>(), "iSubCategoryID", "SubCategory",Model.SubCategories), "--Select SubCategory--", new { id = "ddlSubCategory" })
#Html.ValidationMessage("iSubCategoryID")
</div>
Controller:
[HttpPost]
public ActionResult Create(VendorCreateModel postModel)
{
VendorCreateEditPostValidator createValidator = new VendorCreateEditPostValidator(
postModel.iCategoryID,
postModel.iSubCategoryID,
postModel.AppliedPrograms,
m_unitOfWork.ProgramRepository,
new ModelStateValidationWrapper(ModelState));
if (ModelState.IsValid)
{
int categoryId = int.Parse(postModel.iCategoryID);
int subcategoryId = int.Parse(postModel.iSubCategoryID);
var programIds = postModel.AppliedPrograms.Select(ap => int.Parse(ap));
var programs = m_unitOfWork.ProgramRepository.GetPrograms(programIds);
Vendor vendor = postModel.Vendor;
vendor.Category = m_unitOfWork.CategoryRepository.GetCategory(categoryId);
vendor.SubCategory = m_unitOfWork.SubCategoryRepository.GetSubCategory(subcategoryId);
foreach (Program p in programs)
vendor.Programs.Add(p);
m_unitOfWork.VendorRepository.Add(vendor);
m_unitOfWork.SaveChanges();
return RedirectToAction("Index");
}
VendorCreateModel model = new VendorCreateModel(
postModel.Vendor,
postModel.iCategoryID,
postModel.iSubCategoryID,
postModel.AppliedPrograms,
User.Identity.Name,
m_unitOfWork.CategoryRepository,
m_unitOfWork.SubCategoryRepository,
m_unitOfWork.PermissionRepository);
return View(model);
}
RemoteController:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult SubCategoriesByCateogry(int id)
{
System.Diagnostics.Debug.WriteLine(id);
var SubCategories = db.SubCategories
.Where(v => v.iCategoryID == id)
.OrderBy(v => v.sDesc)
.ToList();
var modelData = SubCategories.Select(v => new SelectListItem()
{
Text = v.sDesc,
Value = v.iSubCategoryID.ToString()
});
return Json(modelData, JsonRequestBehavior.AllowGet);
}
VendorCreateModel:
public class VendorCreateModel
{
public VendorCreateModel()
{
}
public VendorCreateModel(
Vendor vendor,
string categoryId,
string subcategoryId,
IEnumerable<string> appliedPrograms,
string username,
ICategoryRepository categoryRepository,
ISubCategoryRepository subcategoryRepository,
IPermissionRepository permissionRepository)
{
UserHasProgramsValidator programValidator = new UserHasProgramsValidator(username, permissionRepository);
var availablePrograms = programValidator.AvailablePrograms;
HashSet<Category> applicableCategories = new HashSet<Category>();
foreach (var p in availablePrograms)
foreach (var c in categoryRepository.GetCategoriesByProgram(p.iProgramID))
applicableCategories.Add(c);
this.Vendor = vendor;
this.AppliedPrograms = appliedPrograms;
this.Categories = new SelectList(applicableCategories.OrderBy(x => x.sDesc).ToList(), "iCategoryID", "sDesc");
this.SubCategories = new SelectList(subcategoryRepository.GetAllSubCategories().OrderBy(x => x.sDesc).ToList(), "iSubCategoryID", "sDesc");
if (!string.IsNullOrEmpty(categoryId))
{
int temp;
if (!int.TryParse(categoryId, out temp))
throw new ApplicationException("Invalid Category Identifier.");
}
this.iCategoryID = categoryId;
this.iSubCategoryID = subcategoryId;
this.ProgramItems = availablePrograms
.Select(p => new SelectListItem()
{
Text = p.sDesc,
Value = p.iProgramID.ToString(),
Selected = (AppliedPrograms != null ? AppliedPrograms.Contains(p.iProgramID.ToString()) : false)
});
}
public Vendor Vendor { get; set; }
public SelectList Categories { get; set; }
public SelectList SubCategories { get; set; }
public string iCategoryID { get; set; }
public string iSubCategoryID { get; set; }
public IEnumerable<SelectListItem> ProgramItems { get; set; }
[AtLeastOneElementExists(ErrorMessage = "Please select at least one program.")]
public IEnumerable<string> AppliedPrograms { get; set; }
}
I correct the issue and wanted to share in case someone else was banging their head against their desk like Ihave been. Basically I changed the dropdownlistfor to reflect:
#Html.DropDownListFor(model => model.iSubCategoryID, new SelectList(Enumerable.Empty<SelectListItem>(), "iSubCategoryID", "SubCategory",Model.SubCategories), "--Select SubCategory--", new Dictionary<string,object>{ {"class","dropdowns"},{"id","ddlSubCategory"},{"name","iSubCategoryID"}})
Assuming here the problem is in your VendorCreateModel, you either need to add a parameterless constructor or remove it, and create an instance in your action method and populate it by TryUpdateModel. Or parse the form using FormsCollection (not a fan).
You don't have the code for your viewmodel posted here but the basic assumption is that it will map.

Data binding MVC3

I have no idea what am i doing wrong.
Well i have this form, it's part of complex view.
#{
var filtersAjaxOptions = new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "clientList-body",
OnBegin = "clientList.filterRequestStart()",
OnComplete = "clientList.filterRequestComplete()",
OnSuccess = "clientList.filterRequestSuccess()"
};
}
<span class="clientFilters-filterValue inlineBlock">
#using (Ajax.BeginForm(
"Index",
"ClientList",
new {
ProductId = Model.ClientListViewModel.Filters.ProductId,
ClientFilter = Model.ClientListViewModel.Filters.ClientFilter,
BillFilter = Model.ClientListViewModel.Filters.BillFilter,
DateSortType = Model.ClientListViewModel.Filters.DateSortType,
SortDirection = Model.ClientListViewModel.Filters.SortDirection
},
filtersAjaxOptions,
new
{
id = "clientListDateFilter-form"
}
))
{
#Html.TextBoxFor(
m => m.ClientListViewModel.Filters.BeginDateRange,
new
{
#class = "dp-input textInput inlineBlock",
id = "dp-billDateFilterStart",
}
)
#Html.TextBoxFor(
m => m.ClientListViewModel.Filters.EndDateRange,
new
{
#class = "dp-input textInput inlineBlock",
id = "dp-billDateFilterEnd",
}
)
}
</span>
Here's the filters model
public class FilterModel
{
public FilterModel()
{
ClientFilter = ClientsEnum.All;
BillFilter = ClientBillsEnum.All;
}
public string ProductId { get; set; }
public ClientsEnum ClientFilter { get; set; }
public ClientBillsEnum BillFilter { get; set; }
public DateTime? BeginDateRange { get; set; }
public DateTime? EndDateRange { get; set; }
public DateSortType? DateSortType { get; set; }
public SortDirection? SortDirection { get; set; }
}
This part is ClientListController method Index:
public ActionResult Index(FilterModel filters)
{
var clientListViewModel = GetClientListViewModel(filters, 1, 1, PageSize);
if (ControllerContext.HttpContext.Request.IsAjaxRequest())
return PartialView("Partial/ClientListBody", clientListViewModel);
return View(clientListViewModel);
}
Whenever i submit the form above, it turns to me that fields "BeginDateRange" and "EndDateRange" are null and other fields are set properly. Although, when i insert Request.Form in Watch, i can see the whole data.
UPDATE 1
So i set the <globalisation> in Web.config as this:
<globalisation responseHeaderEncoding="utf-8" culture="en-US">
and yet it doesn't work. Very same result as before.
UPDATE 2
Also when i tried to put all the routevalues data into #Html.HiddenFor, controller saw only nulls. And again, Request.Form is filled prprly.
So the question is: how can i bind form data to incoming model?
TY
The default model binder uses the current culture datetime format when binding datetimes. This means that you have to enter the date into the proper format in your textboxes. On the other hand if you need a fixed format you could use a fixed culture in your web.config (<globalization> element) or write a custom model binder: https://stackoverflow.com/a/7836093/29407
UPDATE:
You need to specify the correct binding prefix because your input fields are named like ClientListViewModel.Filters.BeginDateRange but your controller action takes a FilterModel as parameter instead of the root view model:
public ActionResult Index([Bind(Prefix = "ClientListViewModel.Filters")] FilterModel filters)
{
...
}
But now this will break the other values, so you need to adjust your view as well:
#using (Ajax.BeginForm(
"Index",
"ClientList",
null,
filtersAjaxOptions,
new
{
id = "clientListDateFilter-form"
}
))
{
#Html.HiddenFor(x => x.ClientListViewModel.Filters.ProductId)
#Html.HiddenFor(x => x.ClientListViewModel.Filters.ClientFilter)
#Html.HiddenFor(x => x.ClientListViewModel.Filters.BillFilter)
#Html.HiddenFor(x => x.ClientListViewModel.Filters.DateSortType)
#Html.HiddenFor(x => x.ClientListViewModel.Filters.SortDirection)
#Html.TextBoxFor(
m => m.ClientListViewModel.Filters.BeginDateRange,
new
{
#class = "dp-input textInput inlineBlock",
id = "dp-billDateFilterStart",
}
)
#Html.TextBoxFor(
m => m.ClientListViewModel.Filters.EndDateRange,
new
{
#class = "dp-input textInput inlineBlock",
id = "dp-billDateFilterEnd",
}
)
}
or if you want to send them as part of the form url instead if using hidden fields:
#using (Ajax.BeginForm(
"Index",
"ClientList",
new RouteValueDictionary
{
{ "ClientListViewModel.Filters.ProductId", Model.ClientListViewModel.Filters.ProductId },
{ "ClientListViewModel.Filters.ClientFilter", Model.ClientListViewModel.Filters.ClientFilter },
{ "ClientListViewModel.Filters.BillFilter", Model.ClientListViewModel.Filters.BillFilter },
{ "ClientListViewModel.Filters.DateSortType", Model.ClientListViewModel.Filters.DateSortType },
{ "ClientListViewModel.Filters.SortDirection", Model.ClientListViewModel.Filters.SortDirection },
},
filtersAjaxOptions,
new RouteValueDictionary
{
{ "id", "clientListDateFilter-form" }
}
))
{
#Html.TextBoxFor(
m => m.ClientListViewModel.Filters.BeginDateRange,
new
{
#class = "dp-input textInput inlineBlock",
id = "dp-billDateFilterStart",
}
)
#Html.TextBoxFor(
m => m.ClientListViewModel.Filters.EndDateRange,
new
{
#class = "dp-input textInput inlineBlock",
id = "dp-billDateFilterEnd",
}
)
}
Try this:
public ActionResult Index(FilterModel filters, FormCollection collection)
{
UpdateModel(filters, "ClientListViewModel");
var clientListViewModel = GetClientListViewModel(filters, 1, 1, PageSize);
if (ControllerContext.HttpContext.Request.IsAjaxRequest())
return PartialView("Partial/ClientListBody", clientListViewModel);
return View(clientListViewModel);
}
And in view:
#Html.TextBoxFor(
m => m.ClientListViewModel.FilterModel.EndDateRange,
new
{
#class = "dp-input textInput inlineBlock",
id = "dp-billDateFilterEnd",
}
)
You have strange naming. Also it would be better to use hidden fields then passing values through routevalues.

Resources