the paging of Grid.MVC not work - ajax

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"

Related

How to display the collection in the library dynamically Highcharts - Bind collection with Highcharts in MVC

The data from the model under the debugger is correctly displayed in the loop while the graph does not generate. I send two letters to the model - List of periods and a list of orders.
//Model
public class ChartsOrderViewModel
{
public List<DataInfo> ListPeriod { get; set; }
public List<DataInfo> ListQuantity { get; set; }
}
public class DataInfo
{
public string Data { get; set; }
public string Period { get; set; }
public int Quantity { get; set; }
public DataInfo()
{
this.Data = Data;
this.Period = Period;
this.Quantity = Quantity;
}
}
//Controller
public ActionResult ChartsOrder(ChartsOrderViewModel viewModel)
{
List<Order> listaZlecenUzytkownika = new List<Order>();
List<DataInfo> ListaData = new List<DataInfo>();
List<DataInfo> ListaDataPeriod = new List<DataInfo>();
List<DataInfo> ListaDataQuantity = new List<DataInfo>();
ArrayList xValue = new ArrayList();
ArrayList yValue = new ArrayList();
ArrayList ListaxValue = new ArrayList();
listOrderUser = db.Zlecenia.OrderBy(w => w.IdUser).ToList();
ListData = listOrderUser.OrderBy(p => p.DateOfAcceptance).Select(w => new DataInfo { Data = w.DateOfAcceptance.ToString().Substring(0, 7) }).ToList();
ListDataPeriod = ListData.GroupBy(c => c.Data).Select(z => new DataInfo { Period = z.Key }).ToList();
ListDataQuantity = ListData.GroupBy(c => c.Data).Select(z => new DataInfo { Quantity = z.Count() }).ToList();
viewModel.ListPeriod = ListDataPeriod;
viewModel.ListQuantity = ListDataQuantity;
// viewModel.ListPeriod.ToList().ForEach(p => xValue.Add(p.Period));
// viewModel.ListQuantity.ToList().ForEach(p => yValue.Add(p.Quantity));
// ViewData["ListaOkresowCzasowych"] = viewModel.ListaIlosc;
// ViewData["IloscZlecenWOkresie"] = viewModel.ListaIlosc;
return View(viewModel);
}
//View
#model AplikacjaHelpDesk.ViewModels.ChartsOrderViewModel
#{
ViewBag.Title = "Charts";
Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}
<script src="~/Scripts/Highcharts-4.0.1/js/highcharts.js"></script>
<script src="~/Scripts/Highcharts-4.0.1/js/modules/exporting.js"></script>
<h2>Charts Bar</h2>
<div id="chartsBar" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div>
<br />
<script type="text/javascript">
$(function () {
$('#chartsBar').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Period orders'
},
subtitle: {
text: 'Chart'
},
xAxis: {
categories:
[
#foreach (var item in Model.ListPeriod)
{
#item.Period
}
],
},
yAxis: {
min: 0,
title: {
text: 'Quantity'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f}</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
borderWidth: 0
}
},
series: ({
name: 'Ilość',
data: [
#foreach (var item in Model.ListQuantity)
{
#item.Quantity
}
]
})
});
});
</script>
How should the data in the view be displayed in order to display the graph correctly?.That is the number of orders in a given period. I am asking for an example with series data in MVC Highcharts.
Try changing the code responsible for generating categories to this:
categories:
[
#{
var result = "";
foreach (var item in Model.ListPeriod)
{
result += "'" + item.Period +"',";
}
result = result.Remove(result.Length - 1);
}
#Html.Raw(result)
],
and the block that creates data to this:
data: [
#{
var resultQ = "";
foreach (var item in Model.ListQuantity)
{
resultQ += item.Quantity + ",";
}
resultQ = resultQ.Remove(resultQ.Length - 1);
}
#Html.Raw(resultQ)
]

Call MVC4 partial view with Jquery Ajax

I need you help with my mvc4 project. I have 2 drop down menus. When i select firs one, the second is automatically populated with help of Jquery and Ajax. When i select the other one, which is now populated with some data, i need to invoke a method which calls a PL/SQL procedure, and i need to pass a value to that method, which is selected in a second drop down menu.
That method returs some data which I need to pass to my partial view and in that partial view i need to generate a tree view from passed data.
So far i was able to generate TreeView (using jsTree) in my partial view when i hardcoded a value and invoked my method from controler, but i need to do that when i select a value from my second drop down list.
This is my code:
My Controller
public class IndexController : Controller
{
public ActionResult Index()
{
EpfeSelectScreen model = new EpfeSelectScreen();
#region Country
var b = (from a in dbEntitiesErste.CONFIG_COUNTRIES
orderby a.COUNTRY_ID
select new Countries
{
Text = a.COUNTRY_NAME,
Value = a.COUNTRY_ID
});
model.Country = b.OrderBy(x => x.Text).ToList();
#endregion
#region Oracle Stored Procedures
List<TreeNode> list = new List<TreeNode>();
list = ClassData.GetAllClasses(1); //hardcoded value 1 Here goes the value from second drop down list
var TopHierarchy = list.Where(x => x.ParentId == -1).FirstOrDefault();
SetChildren(TopHierarchy, list);
#endregion
var pmViewModel = new MainViewModel
{
FullModelObject = model,
PartialModelObject = TopHierarchy
};
return View(pmViewModel);
}
#region generate Tree
private void SetChildren(TreeNode model, List<TreeNode> list)
{
var childs = list.Where(x => x.ParentId == model.ChildId).ToList();
if (childs.Count > 0)
{
foreach (var child in childs)
{
SetChildren(child, list);
model.Children.Add(child);
}
}
}
#endregion
#region jquery methods
[OutputCache(Duration = 0)]
[HttpGet]
public JsonResult Application(string[] Country)
{
var apl = new List<Applications>();
if (Country[0] == "")
{
//*aplications
var result = (from a in dbEntitiesErste.CONFIG_APPLICATIONS
select new Applications
{
Text = a.APPLICATION_NAME,
Value = a.APPLICATION_ID
});//*.OrderBy(x => x.Text).ToList()
apl.Add(new Applications { Value = 0, Text = "--Please choose application--" });
apl.AddRange(result.OrderBy(x => x.Text).ToList());
}
else
{
var result = (from a in dbEntitiesErste.CONFIG_APPLICATIONS
where Country.Contains(a.COUNTRY_ID)
select new Applications
{
Text = a.APPLICATION_NAME,
Value = a.APPLICATION_ID
}); //*.OrderBy(x => x.Text).ToList();
apl.Add(new Applications { Value = 0, Text = "--Please choose application--" });
apl.AddRange(result.OrderBy(x => x.Text).ToList());
}
var retVal = new { Application = aplikacije };
return Json(retVal, JsonRequestBehavior.AllowGet);
}
//[OutputCache(Duration = 0)]
//[HttpGet]
//public JsonResult Tree(int idApp)
//{
// var ret = (from a in dbEntitiesErste.CONFIG_APPLICATIONS
// select new Applications
// {
// Text = a.APPLICATION_NAME,
// Value = a.APPLICATION_ID
// }).OrderBy(x => x.Text).ToList();
// return Json(ret, JsonRequestBehavior.AllowGet);
//}
#endregion
}
this is my main View (Index.cshtml)
#model EPFE.Models.ViewModels.MainViewModel
<!DOCTYPE html>
#{
ViewBag.Title = "EB";
}
<head>
<title>EBB</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<script src="#Url.Content("~/Scripts/jquery-ui-1.10.3.js")" type="text/javascript"></script>
<script src="~/Scripts/Selections.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="#Url.Content("~/Scripts/jstree.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/Selection.css")" rel="stylesheet" type="text/css" />
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="#Url.Content("~/Content/themes/style.css")" rel="stylesheet" />
<script type="text/javascript">
var pathAplications = '#Url.Action("Application", "Index")';
var pathTreeView = '#Url.Action("Tree", "Index")';
</script>
</head>
<body>
<table>
<tr>
<td>
#Html.DropDownList("Country", new SelectList(Model.FullModelObject.Country, "Value", "Text"), "--Please select Country--")
</td>
</tr>
<tr>
<td>
#Html.DropDownList("Application", new SelectList(Model.FullModelObject.Application, "Value", "Text"), "--Please choose application--")
</td>
</tr>
</table>
<fieldset class="Tree">
<div id="divtree">
<ul id="tree">
<li>
#Model.PartialModelObject.ObjectIdentifier
#Html.Partial("_TreeView", Model.PartialModelObject)
</li>
</ul>
</div>
</fieldset>
</body>
This is my partial view (_TreeView.cshtml)
#model EPFE.TreeViewModel.TreeNode
#foreach (var item in Model.Children)
{
<ul>
#if (item != null)
{
<li>
#item.ObjectIdentifier
#if (item.Children.Count > 0)
{
#Html.Partial("_TreeView", item)
}
</li>
}
</ul>
}
and these are my models
public class EpfeSelectScreen
{
public string Search { get; set; }
public string selectedApplication { get; set; }
public string selectedCountry { get; set; }
public string selectedMetaData { get; set; }
public string selectedTreeView { get; set; }
public List<Countries> Country { get; set; }
public List<Applications> Application { get; set; }
public List<SelectListItem> MetaData { get; set; }
public List<SelectListItem> References { get; set; }
public List<SelectListItem> ReferencedBy { get; set; }
public List<SelectListItem> TreeView { get; set; }
public EpfeSelectScreen()
{
Country = new List<Countries>();
Application = new List<Applications>();
References = new List<SelectListItem>();
ReferencedBy = new List<SelectListItem>();
TreeView = new List<SelectListItem>();
MetaData = new List<SelectListItem>();
}
}
Second one
public class MainViewModel
{
public EpfeSelectScreen FullModelObject { get; set; }
public TreeNode PartialModelObject { get; set; }
public MainViewModel()
{
FullModelObject = new EpfeSelectScreen();
PartialModelObject = new TreeNode();
}
}
and the last one
public class TreeNode
{
public int ParentId { get; set; }
public int ChildId { get; set; }
public int ObjectRelId { get; set; }
public string ObjectIdentifier { get; set; }
public string ObjectTypeId { get; set; }
public IList<TreeNode> Children { get; set; }
public TreeNode()
{
Children = new List<TreeNode>();
}
}
and these are my scripst
$(document).ready(function () {
$("#Country").on('change', CountryChange);
//$("#selectedApplication").on('change', ApplicationChange);
//*
$("#Application").on('change', ApplicationChange);
});
function CountryChange() {
var CountryIds = [];
$("#Country option:selected").each(function (i, selected) {
CountryIds[i] = $(selected).val();
});
$.ajax({
url: pathAplications,
type: 'GET',
data: { Country: CountryIds },
success: function (data) {
var apl = $("#Application");
apl.empty();
for (var j = 0; j < data.Application.length; j++) {
var item = data.Application[j];
var option = "<option value='" + item.Value + "'>" + item.Text + "</option>";
apl.append(option);
}
},
error: function (x, y) {
$("#displayError").html(x.val());
},
traditional: true
});
}
function ApplicationChange() {
var applicationId = [];
$("#Application option:selected").each(function (i, selected) {
applicationId[i] = $(selected).val();
});
$.ajax({
url: pathTreeView,
type: 'GET',
data: { Application: applicationId },
success: function (data) {
var tree = $("#selectedApplication");
trees.empty();
for (var j = 0; j < data.Application.length; j++) {
var item = data.Application[j];
var option = "<option value='" + item.Value + "'>" + item.Text + "</option>";
trees.append(option);
}
},
error: function (x, y) {
$("#displayError").html(x.val());
},
traditional: true
});
}
The function ApplicationChange catches the right value but i don't know how to use it to invoke my method for pl/sql procedure and return that data to partial view.
give your url like this
'#Url.Action("actionname","controllerNmae")',
also make sure if you are making a get or post request then the target action should have that attribute as well.
also you data type will be json for this.
or even better use like this
$.getJSON('#Url.Action("Controller Name here")',
function ()
{
});

ASP.NET MVC AjaxActionLink

My partialview didnot load, i'm using AjaxActionLink
here is my view where i call my partialview
#foreach (var p in Model.Rooms)
{
<div class="room">
<h3>#p.RoomTitle</h3>
<img src="#p.PhotoRoom" alt="room"/>
<h4>#p.TitlePrice</h4>
<blockquote>#p.Description</blockquote>
#Ajax.ActionLink("Order room", "PartialDetail", new { #p.RoomID }, new AjaxOptions { UpdateTargetId = "results", LoadingElementId = "loading",HttpMethod = "POST",InsertionMode = InsertionMode.InsertAfter})
</div>
}
Here is my controller
public PartialViewResult PartialDetail(int roomid)
{
Room rooms =
repository.Room.FirstOrDefault(p => p.RoomID == roomid);
var viewModel = new RoomEditViewModel
{
RoomID = rooms.RoomID,
RoomTitle = rooms.RoomTitle,
Description = rooms.Description,
PhotoRoom = rooms.PhotoRoom
};
ViewBag.room = roomid;
return PartialView(viewModel);
}
fixed your ajax action link
What you set
#Ajax.ActionLink("Order room", "PartialDetail", new { #p.RoomID }
Should be
#Ajax.ActionLink("Order room", "PartialDetail", new { roomid = #p.RoomID }
As a recommendation set the aceepted protocols in your action
[HttpPost]
public PartialViewResult PartialDetail(int roomid)

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.

Using MultiSelect List in 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();

Resources