I have a mvcjqgrid:
#(Html.Grid("dataGrid")
.SetJsonReader(new MvcJqGrid.DataReaders.JsonReader { Id = "Id", RepeatItems = false })
.SetRequestType(RequestType.Post)
.AddColumn(new Column("Name").SetLabel("Name").SetSearch(true))
.AddColumn(new Column("Email").SetLabel("E-Mail").SetSearch(true).SetFormatter(Formatters.Email))
.AddColumn(new Column("Phone").SetLabel("Phone").SetSearch(true))
.SetSearchToolbar(true)
.SetUrl(Url.Action("GetData", "Controller"))
.SetSearchOnEnter(false)
.SetRowNum(10)
.SetRowList(new[] { 10, 15, 20, 50 })
.SetViewRecords(true)
.SetPager("pager"))
and controller:
public ActionResult GetData()
{
return View(new myEntity[0]);
}
[HttpPost]
public JsonResult GetData(GridSettings gridSettings)
{
int totalRecords = DataHelper.GetCount();
var data = DataHelper.GetData(gridSettings);
var jsonData = new
{
total = totalRecords / gridSettings.PageSize + 1,
page = gridSettings.PageIndex,
records = totalRecords,
rows = data
};
return Json(jsonData);
}
EDIT:
so my question is how can i store GridSettings in session in right way, i need every time user backs to this page, page should be the same as when he left?
If i do:
Session["settings"] = gridSettings;
i need some way to compare stored gridSettings with the one passed to action.
Why don't you use the Http Cache for this case? We can write a caching provider, and Http Cache is one implementation for this. So in the future you can extend more providers for it.
The answer is to recreate Grid:
#{
var setting = Session["settings"] as GridSettings;
}
#(Html.Grid("dataGrid")
.SetJsonReader(new MvcJqGrid.DataReaders.JsonReader { Id = "Id", RepeatItems = false })
.SetRequestType(RequestType.Post)
.AddColumn(new Column("Name").SetLabel("Name").SetSearch(true))
.AddColumn(new Column("Email").SetLabel("E-Mail").SetSearch(true).SetFormatter(Formatters.Email))
.AddColumn(new Column("Phone").SetLabel("Phone").SetSearch(true))
.SetSearchToolbar(true)
.SetUrl(Url.Action("GetData", "Controller"))
.SetSearchOnEnter(false)
.SetRowNum(setting != null?setting.PageSize : 10)
.SetPage(setting != null?setting.PageIndex : 1);
.SetSortName(setting != null?setting.SortColumn : "");
.SetRowList(new[] { 10, 15, 20, 50 })
.SetViewRecords(true)
.SetPager("pager"))
Related
I have an MVC site that is connected to a database with multiple tables. Some of the tables have only 1000 or so records, so searching through those is fairly simple. However, one of the tables has over 2 million records, and I tried implementing the same searching method but it is far too slow. For the tables with less records, the search goes through every column looking for matches, but the table with a million records can only search through one column in an efficient manner. Essentially, what I want to do to fix this problem is to allow the user to search through the search results. So if I were to search by apple in the table with a million records, let's say that 100,000 records remain. Then, I could search by Gala on the remaining 100,000 records to narrow the results down even more. Is this possible? Or is there possibly a better way to search through this many records that I am not thinking of?
Controller
public ViewResult Index(string sortOrder, string currentFilter, string search, int? page, int? pageSize)
{
int pageIndex = 1;
pageIndex = page.HasValue? Convert.ToInt32(page) : 1;
int defaSize = (pageSize ?? 25);
ViewBag.psize = defaSize;
ViewBag.PageSize = new List<SelectListItem>()
{
new SelectListItem() { Value = "25",Text = "25"},
new SelectListItem() { Value = "50",Text = "50"},
new SelectListItem() { Value = "100",Text = "100"},
new SelectListItem() { Value = "1000",Text = "1000"},
};
ViewData["ControllerName"] = this.ToString();
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "pkDeviceUnderTest" : "";
if (search == null)
{
ViewBag.TotalCount = dbModel.DeviceUnderTests.Count();
}
else
{
var ld = dbModel.DeviceUnderTests.Where(x => x.nkDeviceUnderTest.Contains(search)||x.nkNotes.Contains(search)||x.FaultApplication.nkFaultApplication.Contains(search)||x.Firmware.nkFirmware.Contains(search)
||x.Hardware.nkHardware.Contains(search)||x.Location.nkLocation.Contains(search)||x.Power.nkPower.Contains(search)||x.nkHandleRating.ToString().Contains(search)||x.nkPreEventTime.ToString().Contains(search)).ToList()
.Count();
ViewBag.TotalCount = ld;
}
ViewBag.cf = currentFilter;
ViewBag.search = search;
Session["searchcircuit"] = search;
ViewBag.defaSize = defaSize;
var div = ViewBag.TotalCount / defaSize;
ViewBag.numofPages = ((ViewBag.defaSize - 1) + ViewBag.TotalCount) / ViewBag.defaSize;
ViewBag.index = pageIndex;
int pagenum = pageIndex;
var records = dbModel.DeviceUnderTests.Where(x => x.nkDeviceUnderTest.Contains(search) || x.nkNotes.Contains(search) || x.FaultApplication.nkFaultApplication.Contains(search) || x.Firmware.nkFirmware.Contains(search)
|| x.Hardware.nkHardware.Contains(search) || x.Location.nkLocation.Contains(search) || x.Power.nkPower.Contains(search) || x.nkHandleRating.ToString().Contains(search) ||search==null|| x.nkPreEventTime.ToString().Contains(search)).OrderBy(x => x.pkDeviceUnderTest).Skip(defaSize * (pagenum - 1)).Take(defaSize);
var result = new StaticPagedList<DeviceUnderTest>(records, pageIndex, defaSize, ViewBag.TotalCount);
return View(result);
}
View
#using (Html.BeginForm("Index", "Circuit", FormMethod.Get))
{
<input type="text" name="search" placeholder="Search ... " />
<input type="submit" name="submit" value="Search" class="btn btn-default" style="background-color:#337ab7;color:azure" />
}
I am using the bootstrap selectpicker for a multiselect dropdown menu to filter items of a table in a mvc5 web app. Everything works fine so far, but i am having trouble to keep the selected filters selected after submitting. So i can read the selected filters in the controller, but after that, there is only the first previously selected filter still shown as selected after the submit. I want all chosen filters to be still selected. How can I reach this?
Here ist my Code, the ViewModel contains:
public MultiSelectList AvailableUser_ID { get; set; }
private List<string> _selectedUserId = new List<string>();
public List<string> SelectedUserId
{
get { return _selectedUserId; }
set { _selectedUserId = value; }
}
The Controller (Post):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "SelectedUserId,SelectedUserInteractionTypesId")] IndexUserInteractionViewModel indexUserInteractionViewModel)
{
indexUserInteractionViewModel.UserInteractionViewModels = new List<UserInteractionViewModels>();
indexUserInteractionViewModel.AvailableUser_ID = new MultiSelectList(db.AspNetUsers.ToList(), "Id", "Email", indexUserInteractionViewModel.SelectedUserId);
// Filter Function: selectedUserId contains all the Ids of the previously selected filters
foreach (string selectedUserId in indexUserInteractionViewModel.SelectedUserId)
{
if (userInteraction.AspNetUsers_Id.Equals(selectedUserId))
// ...
}
}
And the View:
<script type="text/javascript">
$(document).ready(function () {
$('.selectpicker').selectpicker();
});
</script>
<th>#Html.DropDownListFor(Model => Model.SelectedUserId, Model.AvailableUser_ID as MultiSelectList, new { #id = "userFilter", #class = "selectpicker", #multiple = "mulitple", data_live_search = "true" })</th>
So how can I keep the Selection selected?
Unfortunately I have little js-knowledge and i am assuming that i could solve it in the js-script. I am hoping for some experts here. Thank you!
A colleague of mine found a solution, this is what works:
var selectedList = #Html.Raw(Json.Encode(Model.SelectedUserId));
if(selectedList.length > 0){
var result = '[';
for (i = 0; i < selectedList.length; i++) {
result += '"' + selectedList[i] + '",';
}
result = result.slice(0, -1); //remove last comma
result += ']';
$('.selectpicker').selectpicker('val', JSON.parse(result1));
}else{
$('.selectpicker').selectpicker();
}
This is code snippet for load 15 text areas into an Add_New_Product form page.
public ActionResult Add_Product(int? page)
{
var dummyItems = db.AB_ProductTypeCategoryField;
var pager = new PaginationModel.Pager(dummyItems.Count(), page);
var model = new AddNewProduct
{
ListProductFields = dummyItems.OrderBy(i => i.ProductFieldID).Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize).ToList(),
Pager = pager
};
return View(model);
}
Since in this form page has many text areas(like 15) ,I limited with pagination , one text area per one page.
this is the view
I want use above ListProductFields data iteratvely inside same above method.
But once I insert the a value to first text area and then go to next text area , again if I click previous button , then first text area's added values are disappearing.
I decided to come up with sessions , So I changed above code as follows
Attempt 1:
public ActionResult Add_Product(int? page, AddNewProduct sample)
{
AddNewProduct newmodel = sample;
AddNewProduct newmodels = Session["TemplateData"] as AddNewProduct;
var dummyItems = db.AB_ProductTypeCategoryField;
var pager = new PaginationModel.Pager(dummyItems.Count(), page);
var model = new AddNewProduct
{
ListProductFields = dummyItems.OrderBy(i => i.ProductFieldID).Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize).ToList(),
Pager = pager
};
Session["TemplateData"] = model;
return View(model);
}
Edit
Attempt 2:
public ActionResult Add_Product(int? page, AddNewProduct sample)
{
TempData["AddNewProduct"] = sample;
AddNewProduct book = TempData["AddNewProduct"] as AddNewProduct;
var dummyItems = db.AB_ProductTypeCategoryField;
var pager = new PaginationModel.Pager(dummyItems.Count(), page);
var model = new AddNewProduct
{
ListProductFields = dummyItems.OrderBy(i => i.ProductFieldID).Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize).ToList(),
Pager = pager
};
sample = model;
return View(model);
}
But it doesn't keep any value
I have a problem in my asp.net mvc4 application :
i'am passing two integers as a parameteres to an action :
<a>#Html.ActionLink(s, "Gerer_Sequence", "Travail", new { seq = Model[k][i].Id_séquence , affa = aff.Id_affaire } )</a>
the action is :
public ActionResult Gerer_Sequence(int seq, int affa)
{
Session["affaire"] = affa;
Session["sequence"] = seq;
return RedirectToAction("Index", "Calendar");
}
the problem is that the parameters are null however the its values are 3 and 1 in the model.
So what is the problem? How can i modify my code to fix the error?
Try this.
<td>
#Html.ActionLink("EditUser", "Index", new { Id = m.ID,Name = m.Name })
</td>
public ActionResult Index(string Id, string Name)
{
var model = new RegisterModel();
int _ID = 0;
int.TryParse(Id, out _ID);
if (_ID > 0)
{
RegisterModel register = GetRegisterUserById(_ID);
model.ID = _ID;
model.Name = register.Name;
model.Address = register.Address;
model.PhoneNo = register.PhoneNo;
}
return View(model);
}
You just need to change this:
new { seq = Model[k][i].Id_séquence , affa = aff.Id_affaire }
to this:
new RouteValueDictionary { { "seq", Model[k][i].Id_séquence }, { "affa", aff.Id_affaire } }
because the fourth parameter you're using is the route values.
Try this:
#Html.ActionLink(s, "Gerer_Sequence", "Travail", new { seq = Model[k][i].Id_séquence , affa = aff.Id_affaire }, null )
Remove the tag
Ensure that parameters you have provided are int values.
After that run your application and check the link generated, if values are ok then it should be ok.
i put the action in the same controller:
#Html.ActionLink("Gerer Sequence", "Gerer_Sequence", new { seq = Model[k][i].Id_séquence , affa = aff.Id_affaire } )
Check This Code Sniplet out.
using (AttendanceDataContext db = new AttendanceDataContext())
{
var attendance = db.attendpunches.Select(at => new RawEmployeeCheckInOutInfo
{
CheckTime = at.punchtime.Value,
Direction = ((AttendanceDirection)at.direction.Value).ToString()
});
...
AttendanceDirection is enum Which is...
public enum AttendanceDirection : int
{
CheckIn = 1,
CheckOut = 2
}
The Problem is The Direction = ((AttendanceDirection)at.direction.Value).ToString() is always returning the byte value.
I suspect the problem is that the ToString is being effectively performed at the database side, which doesn't know the enum names. Try this:
var attendance = db.attendpunches
.Select(at => new { CheckTime = at.punchtime.Value,
Direction = at.direction.Value })
.AsEnumerable() // Do the rest of the query in-process...
.Select(at => new RawEmployeeCheckInOutInfo {
CheckTime = at.CheckTime,
Direction = ((AttendanceDirection) at.Direction).ToString()
});