I have a table in the web application from where the users can make orders. The table shows the Quantity that is available and we need to let users enter the quantity they need like below
when the Order button is clicked I want to validate if the user is entering the Quantity Required is greater than the Quantity Avail. Every time the Order button is clicked it calls the Controller to retrieve the data and check against the quantity. The view is like below
#model JAXSurplusMouseApp.Models.CustomerInventoryCollectionDataModel
#{
ViewData["Title"] = "Index";
}
<h3>Order Surplus Mouse</h3>
<div class="col-md-9">
<table class="table">
<thead>
<tr>
<th>
Strain ID
</th>
<th>
Strain Name
</th>
<th>
Quantity Avail
</th>
<th>
Room Number
</th>
<th>
Quantity Required
</th>
<th></th>
</tr>
</thead>
<tbody>
#{var custID = Model.CustomerData; }
#foreach (var item in Model.Inventorys)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.StrainId)
</td>
<td>
#Html.DisplayFor(modelItem => item.StrainName)
</td>
<td>
#Html.DisplayFor(modelItem => item.QuantityAvailable)
</td>
<td>
#Html.DisplayFor(modelItem => item.RoomNumber)
</td>
<td>
<form method="post"
asp-controller="Inventories"
asp-action="OrderItem">
<row>
<column>
<input type="text" id="quantityReq" name="quantityReq" value=#item.QuantityReq size="4" />
<input type="hidden" id="customerID" name="customerID" value="#custID.CustomerId" />
<input type="hidden" id="invetoryID" name="invetoryID" value="#item.InventoryId" />
<button type="submit" style="border: none; background-color: transparent; color: #1a0dab "><u>Order</u></button>
</column>
</row>
</form>
</td>
</tr>
}
</tbody>
</table>
#{
var prevDisabled = !Model.Inventorys.HasPreviousPage ? "disabled" : "";
var nextDisabled = !Model.Inventorys.HasNextPage ? "disabled" : "";
}
<a asp-action="Index"
asp-route-sortOrder="#ViewData["CurrentSort"]"
asp-route-pageNumber="#(Model.Inventorys.PageIndex - 1)"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
class="btn btn-default #prevDisabled"> Previous </a>
<a asp-action="Index"
asp-route-sortOrder="#ViewData["CurrentSort"]"
asp-route-pageNumber="#(Model.Inventorys.PageIndex + 1)"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
class="btn btn-default #nextDisabled"> Next </a>
</div>
</div>
And Controller action I am calling when clicking on the button is
public async Task<IActionResult> OrderItem(int? customerID, int? invetoryID, int quantityReq)
{
if (customerID == null || invetoryID == null || quantityReq == 0)
{
return NotFound();
}
Customer custData = await _context.Customers.FindAsync(customerID);
var intData = await _context.Inventories.FindAsync(invetoryID);
if (quantityReq <= intData.QuantityAvailable)
{
MouseOrder mo = new MouseOrder();
mo.CustomerId = (int)customerID;
mo.OrderDate = DateTime.Now;
mo.SamaccountName = "dvella";
_context.Add(mo);
await _context.SaveChangesAsync();
InventoryOrder io = new InventoryOrder();
io.OrderId = mo.MouseOrderId;
io.OrderQuantity = quantityReq;
io.InventoryId = (int)invetoryID;
_context.Add(io);
await _context.SaveChangesAsync();
intData.QuantityAvailable = intData.QuantityAvailable - quantityReq;
_context.Update(intData);
await _context.SaveChangesAsync();
}
else if (quantityReq > intData.QuantityAvailable){
}
return RedirectToAction("Index", "Inventories", new { id = customerID });
}
Get action in the Controller is like below
// GET: Inventories
public async Task<IActionResult> Index(int? id, string sortOrder, string searchString,
int? pageNumber, string currentFilter)
{
if (id == null)
{
return NotFound();
}
ViewData["StockParam"] = String.IsNullOrEmpty(sortOrder) ? "st_desc" : "";
ViewData["CurrentFilter"] = searchString;
ViewData["CurrentSort"] = sortOrder;
if (searchString != null)
{
pageNumber = 1;
}
else
{
searchString = currentFilter;
}
var inventories_data = from s in _context.Inventories
where s.QuantityAvailable >0
select s;
if (!String.IsNullOrEmpty(searchString))
{
inventories_data = inventories_data.Where(s => s.StrainCode.Contains(searchString));
}
switch (sortOrder)
{
case "st_desc":
inventories_data = inventories_data.OrderByDescending(s => s.StrainCode);
break;
default:
inventories_data = inventories_data.OrderBy(s => s.StrainCode);
break;
}
int pageSize = 15;
Customer custData = await _context.Customers.FindAsync(id);
var inventories = await PaginatedList<Inventory>.CreateAsync(inventories_data.AsNoTracking(), pageNumber ?? 1, pageSize);
var model = new CustomerInventoryCollectionDataModel
{
CustomerData = custData,
Inventorys = inventories
};
return View(model);
}
Model Class is like
public class CustomerInventoryCollectionDataModel
{
public Customer CustomerData { get; set; }
public PaginatedList<Inventory> Inventorys { get; set; }
}
Where the Inventory Class is like
public partial class Inventory
{
public string StrainId { get; set; }
public string StrainName { get; set; }
public int QuantityAvailable { get; set; }
public string RoomNumber { get; set; }
public int InventoryId { get; set; }
[NotMapped]
public int? QuantityReq { get; set; }
}
I am developing a web application for the first time using the .NET Core with EF and kind of stuck with this. Please Suggest me how can I handle the validation here. I am here not so particular where the validation message should be shown but a way to notify the users to enter the correct number. I appreciate all the help
****EDIT ****
I see the error like
When I enter less or more than the the Quantity Available it is not doing anything, in the devtools I see the error like the screenshot
Uncaught SyntaxError: Function statements require a function name
Before pressing the Buy Now button the URL is like https://localhost:44330/Inventories/Index/460 Any after I pressed the https://localhost:44330/Inventories/Index/460#
I am not able to troubleshoot more , kind of stuck here
try this. Since it is using ajax I removed a form and a submit button
#model JAXSurplusMouseApp.Models.CustomerInventoryCollectionDataModel
#{
ViewData["Title"] = "Index";
}
<h3>Order Surplus Mouse</h3>
<table>
<thead>
<tr>
<th style="padding-right:1em">
Strain ID
</th>
<th style="padding-right:1em">
Strain Name
</th>
<th style="padding-right:1em">
Room
</th>
<th style="padding-right:1em">
Quantity Avail
</th>
<th>
Quantity Required
</th>
<tbody>
#foreach(var item in Model.Inventorys)
{
<tr>
<td />
<td />
<td />
<td />
<td style="padding-right:1em">
<input type="text" class="text-danger float-right" style="border:none;font-size: smaller" id="#("errorMessage"+#item.InventoryId)" readonly />
</td>
</tr>
<tr style="padding-left:2em">
<td>
#Html.DisplayFor(modelItem => item.StrainId)
</td>
<td>
#Html.DisplayFor(modelItem => item.StrainName)
</td>
<td>
#Html.DisplayFor(modelItem => item.RoomNumber)
</td>
<td>
#Html.DisplayFor(modelItem => item.QuantityAvailable)
</td>
<td>
<row>
<column>
<input type="text" style="text-align:right;padding-right:1em" id="#("quantityReq"+#item.InventoryId)" name="quantityReq" value="#item.QuantityReq" />
</column>
<column>
<input type="hidden" id="#("customer"+#item.InventoryId)" name="customerID" value="#Model.CustomerData.Id" />
<input type="hidden" id="#("inventory"+#item.InventoryId)" name="invetoryID" value="#item.InventoryId" />
Buy now
</row>
</td>
</tr>
}
</tbody>
</table>
#section Scripts {
<script type="text/javascript">
$(document).ready(function () {
$(document).on("click", ".buyNow", (function (e) {
e.preventDefault();
e.stopImmediatePropagation();
var id=$(this).data("id");
onBuyNow(id);
}));
function onBuyNow(id) {
$("#errorMessage" + id).val("");
var quantityReq = $("#quantityReq"+id).val();
var customerId = $("#customer"+id).val();
var data = {
customerId: customerId,
quantityReq: quantityReq,
inventoryId: id
};
$.ajax({
url: '#Url.Action("OrderItem", "Inventories")',
dataType: 'json',
type: 'POST',
data: data,
success: function (result) {
if (result.status !== "Ok") {
$("#errorMessage" + result.inventoryId).val("available only " + result.available);
}
else {
var url = '#Url.Action("Index", "Inventories")';
url=url++"?id="+customerId;
alert("url: " + url);
window.location.href = url;
};
error: function (error) {
alert("error");
}
});
};
}
});
</script>
}
action
public async Task<ActionResult> OrderItem(int? customerID, int? inventoryID, int quantityReq)
{
if (customerID == null || invetoryID == null || quantityReq == 0)
{
return NotFound();
}
Customer custData = await _context.Customers.FindAsync(customerID);
var intData = await _context.Inventories.FindAsync(inventoryID);
if (quantityReq <= intData.QuantityAvailable)
{
... your code
}
else if (quantityReq > intData.QuantityAvailable){
return Ok( new { status = "NotAvailable", inventoryId=inventoryId, available = intData.QuantityAvailable} );
}
return Ok(new { status="Ok" } );
}
and the bottom of a body section of your layout should have
<script src="~/lib/jquery/dist/jquery.min.js"></script>
#await RenderSectionAsync("Scripts", required: false)
Related
I'm trying to make a table that has searching, sorting, and filtering (any number of available filters). When I sort the filters get overwritten and I'm not sure how to make sure they stay in the querystring since they are stored in the model as an array of strings.
I've tried using the ViewBag and the asp-route-varName tag but it didn't work since it's an array. I thought since they are all in the same form that they should just append to the querystring not overwrite it. The sort and search works since search is just a string. The filter and search works not entirely sure why.
View:
#model ScenarioLake.Api.Host.WebApplication.Models.MasterModel;
<form asp-controller="FileList" asp-action="Index" method="get">
<p>
Title: <input type="text" name="SearchString" />
<input type="submit" value="Filter" />
<a asp-action="Index">Full List</a>
</p>
<select class="chosen-select" multiple="multiple" name="filters" asp-for="filters"
asp-items="Model.filterModel.filters[0].values;"></select>
<input type="submit" />
<table class="table">
<thead>
<tr>
<th>
<a asp-controller="FileList" asp-action="Index" asp-route-searchString="#Model.searchString" asp-route-sortOrder="#ViewData["NameSortParm"]">
#Html.DisplayNameFor(model => model.files.FirstOrDefault().Name)
</a>
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.files)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Guid">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Guid">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Guid">Delete</a>
</td>
</tr>
}
</tbody>
</table>
</form>
Model:
public class MasterModel
{
public FilterFileModel filterModel { get; set;}
public List<FileDisplay> files;
public string[] filters { get; set; }
public string searchString { get; set; }
}
Controller Index Method:
public async Task<IActionResult> Index(string sortOrder, string searchString, MasterModel model)
{
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
IGetFileListHandler fileListHandler = _restServiceFactory.CreateGetFileListHandler();
GetFileListRequest fileListRequest = new GetFileListRequest();
IGetFileListResponse response = await fileListHandler.ProcessRequest(fileListRequest);
var items = new List<FileDisplay>();
IGetFileAttributesHandler fileAttributesHandler = _restServiceFactory.CreateGetFileAttributesHandler();
GetFileAttributesRequest fileAttributesRequest = new GetFileAttributesRequest();
IGetFileAttributesResponse fileAttributesResponse = await fileAttributesHandler.ProcessRequest(fileAttributesRequest);
IGetFileFileAttributeHandler fileFileAttributesHandler = _restServiceFactory.CreateGetFileFileAttributeHandler();
GetFileFileAttributeRequest fileFileAttributesRequest = new GetFileFileAttributeRequest();
IGetFileFileAttributeResponse fileFileAttributesResponse = await fileFileAttributesHandler.ProcessRequest(fileFileAttributesRequest);
var fileFileAttribute = fileFileAttributesResponse.FileFileAttributes;
IEnumerable<Entities.Public.Interfaces.IFile> responseFilteredFiles = response.Files;
FilterFileModel fileFilter = new FilterFileModel();
fileFilter.filters = new List<FileFilter>();
if (!ReferenceEquals(fileAttributesResponse, null) && !ReferenceEquals(fileAttributesResponse.Values, null))
{
fileFilter.types = fileAttributesResponse.Values.Select(s => s.Type).Distinct().ToList(); // query fileattribute repo to get all types of filters
foreach (var type in fileFilter.types)
{
FileFilter filter = new FileFilter();
filter.type = type;
filter.values = fileAttributesResponse.Values.Where(s => s.Type == type).Select(s => new SelectListItem()
{
Value = s.Value,
Text = s.Value
}).Distinct().ToList();
fileFilter.filters.Add(filter);
}
}
if (!ReferenceEquals(response, null) && !ReferenceEquals(response.Files, null))
{
if (!String.IsNullOrEmpty(searchString))
{
responseFilteredFiles = responseFilteredFiles.Where(s => s.FileName.Contains(searchString));
model.searchString = searchString;
}
switch(sortOrder)
{
case "name_desc":
responseFilteredFiles = responseFilteredFiles.OrderByDescending(s => s.FileName);
break;
default:
responseFilteredFiles = responseFilteredFiles.OrderBy(s => s.FileName);
break;
}
}
if (model.filters != null)
{
if (model.filters.Length != 0)
{
IEnumerable<int> attributeIds = fileAttributesResponse.Values.Where(s => model.filters.Contains(s.Value)).Select(s => s.FileAttributeId);
IEnumerable<int> fileIds = fileFileAttribute.Where(s => attributeIds.Contains(s.FileAttributeId)).Select(s => s.FileId);
responseFilteredFiles = responseFilteredFiles.Where(s => fileIds.Contains(s.FileId));
}
}
foreach (var item in responseFilteredFiles)
{
var file = new FileDisplay()
{
Name = item.FileName,
Guid = item.Guid,
FileId = item.FileId
};
items.Add(file);
}
model.filterModel = fileFilter;
model.files = items;
return View(model);
}
The expected result is that the filter and search data persists when a user changes the sort. The actual results are only the search persists, I don't care about the sort persisting when the filters or search are changed.
If someone can help, I would be very thankful.
I'm using C# in VS 2017 for an ASP.net Application.
In a razor view, I have this code:
<div class="text-center" >
<ul class="pagination">
#for (var i = 1; i <= ViewBag.SearchMetaData.SearchNumberOfPages; i++)
{
if (ViewBag.SearchMetaData.SearchCurrentPage == #i)
{
<li class="active"> #Html.ActionLink(#i.ToString(), "CI_SequenceBlocks_Pager_Form_Handler", new { id = #i, value = ViewBag.SearchMetaData.SearchString, inInstitutionProgramID = ViewData["SelectedInstitutionProgram"].ToString() },null)</li>
}
else
{
<li> #Html.ActionLink(#i.ToString(), "CI_SequenceBlocks_Pager_Form_Handler", "Home", new { id = #i, value = ViewBag.SearchMetaData.SearchString, inInstitutionProgramID = ViewData["SelectedInstitutionProgram"].ToString() },null)</li>
}
}
</ul>
</div>
}
It works great on my development machine. The actionlinks never fail.
However, when I publish to the server, I can click on the links 3 or 4 times and they work. After the 4th time, it is like the variables are forgotten. When I view the page source the links appear to correct. It seems to me something on the server is being reset. Does anyone have any ideas?
Here is more code:
____________EDIT AFTER THIS LINE__________________
Controller:
public ActionResult CI_SequenceBlocks()
{
string strIP = "";
string strSRCHString = "";
string strSRCHstringQry = "";
int intSRCHRequestedPage = 1;
int intSRCHPageSize = 10;
if (TempData["CI_SequenceBlocks_InstitutionProgram"] == null)
{
strIP = "0";
strSRCHString = "";
}
else
{
strIP = TempData["CI_SequenceBlocks_InstitutionProgram"].ToString();
strSRCHString = TempData["CI_SequenceBlocks_SRCHString"]?.ToString() ?? "";
};
ViewData["listInstitutionPrograms"] = new SelectList(MSSQL_CI_Repository.ListInstitutionProgramsForComboBoxes(), "Value", "Text");
ViewData["SelectedInstitutionProgram"] = strIP;
ViewData["inSRCHString"] = strSRCHString;
ViewBag.SRCHString = strSRCHString;
//ViewBag.InstitutionalProgram = strIP;
if (strSRCHString == "") { ViewBag.SRCHDescriptor = "NO_SEARCH_TERM"; } else { ViewBag.SRCHDescriptor = strSRCHString?.ToString() ?? "NO_SEARCH_TERM"; }
if (strSRCHString.Trim() == "")
{
strSRCHstringQry = "rttyghujmgdddh";
}
else
{
strSRCHstringQry = strSRCHString;
}
if(TempData["CI_SequenceBlocks_RequestedPage"] != null)
{
intSRCHRequestedPage = Convert.ToInt32(TempData["CI_SequenceBlocks_RequestedPage"]);
}
vm_CI_SequenceBlocksWithSearchMetaData obj = MSSQL_CI_Repository.ListCI_SequenceBlocksByInstitutionalProgramForFullTextSearch(Convert.ToInt32(strIP), strSRCHstringQry,intSRCHPageSize,intSRCHRequestedPage);
ViewBag.SearchMetaData = obj.SearchMetaData;
var model = obj.lstSequenceBlocks;
return View(model);
}
[HttpPost]
public ActionResult CI_SequenceBlocks_FullTextSearch(FormCollection form)
{
TempData["CI_SequenceBlocks_InstitutionProgram"] = form["HidInstitutionProgram"].ToString();
TempData["CI_SequenceBlocks_SRCHString"] = form["SRCHString"].ToString();
TempData["CI_SequenceBlocks_RequestedPage"] = 1;
return RedirectToActionPermanent("CI_SequenceBlocks");
}
public ActionResult CI_SequenceBlocks_Edit_Form_Handler(int id, string value, int inInstitutionProgramID)
{
TempData["CI_SequenceBlocks_InstitutionProgramID"] = inInstitutionProgramID;
TempData["CI_SequenceBlocks_SequenceBlockID"] = id;
if (value == "Edit_SequenceBlock_ID")
{
return RedirectToAction("CI_SequenceBlock_Edit");
}
else if (value == "Maintain_SequenceBlock_ID")
{
return RedirectToAction("CI_SequenceBlock_Maintain");
}
else
{
TempData["CI_SequenceBlocks_InstitutionProgram"] = inInstitutionProgramID;
return RedirectToAction("CI_SequenceBlocks");
}
}
public ActionResult CI_SequenceBlocks_Pager_Form_Handler(int id, string value, int inInstitutionProgramID)
{
TempData["CI_SequenceBlocks_InstitutionProgram"] = inInstitutionProgramID;
TempData["CI_SequenceBlocks_SRCHString"] = value;
TempData["CI_SequenceBlocks_RequestedPage"] = id;
return RedirectToActionPermanent("CI_SequenceBlocks");
}
[HttpPost]
public ActionResult CI_SequenceBlocks_ProgramChange(FormCollection form)
{
TempData["CI_SequenceBlocks_InstitutionProgram"] = form["SelectedInstitutionProgram"].ToString();
return RedirectToActionPermanent("CI_SequenceBlocks");
}
RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}/{id2}/{id3}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, id2 = UrlParameter.Optional, id3 = UrlParameter.Optional }
);
}
Full Razor Code:
#model IEnumerable<UTCI_Manager.Models.vm_CI_SequenceBlock>
#{
ViewBag.Title = "CI_SequenceBlocks";
}
<h2>CI_SequenceBlocks</h2>
#using (Html.BeginForm("CI_SequenceBlocks_ProgramChange", "Home", FormMethod.Post, new { id = "submitForm" }))
{
#Html.DisplayNameFor(model => model.InstitutionProgramID)
#Html.DropDownList("SelectedInstitutionProgram", (SelectList)ViewData["listInstitutionPrograms"], new { onchange = "this.form.submit();" })
}
#using (Html.BeginForm("CI_Sequenceblocks_FullTextSearch", "Home", FormMethod.Post, new { id = "submitForm" }))
{
if (ViewData["SelectedInstitutionProgram"].ToString() != "0")
{
<div class="input-group">
#Html.Hidden("HidInstitutionProgram", ViewData["SelectedInstitutionProgram"]?.ToString() ?? "0")
#Html.TextBox("SRCHString", ViewData["inSRCHString"].ToString(), new { #class = "form-control", #placeholder = "Search" })
<span class="input-group-btn">
<button class="btn btn-info" type='submit' value="Search">Search</button>
</span>
</div>
}
}
<table class="table table-striped" summary="List of Sequence Blocks">
<tr>
#* <th>
#Html.DisplayNameFor(model => model.SequenceBlockID)
</th>
<th>
#Html.DisplayNameFor(model => model.InstitutionProgramID)
</th>
*#
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayNameFor(model => model.SequenceBlockDescription)
</th>
<th>
#Html.DisplayNameFor(model => model.SequenceBlockRequired)
</th>
#* <th>
#Html.DisplayNameFor(model => model.Minimum)
</th>
<th>
#Html.DisplayNameFor(model => model.Maximum)
</th>
*#
<th>
#Html.DisplayNameFor(model => model.SequenceBlockTimingMethod)
</th>
<th>
#Html.DisplayNameFor(model => model.Duration)
</th>
<th>
#Html.DisplayNameFor(model => model.StartDate)
</th>
<th>
#Html.DisplayNameFor(model => model.EndDate)
</th>
<th>
#Html.DisplayNameFor(model => model.ClerkshipModel)
</th>
<th>
#using (Html.BeginForm("CI_SequenceBlocks_AddSequenceBlock", "Home", FormMethod.Post, new { id = "submitForm" }))
{
if (ViewData["SelectedInstitutionProgram"].ToString() != "0")
{
#Html.Hidden("HidInstitutionalProgram", ViewData["SelectedInstitutionProgram"].ToString())
<input type="submit" value="Add Sequence Block" class="btn btn-sm" />
}
}
</th>
</tr>
#foreach (var item in Model)
{
<tr>
#Html.HiddenFor(modelItem => item.SequenceBlockID)
#Html.HiddenFor(modelItem => item.InstitutionProgramID)
#Html.HiddenFor(modelItem => item.Minimum)
#Html.HiddenFor(modelItem => item.Maximum)
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.SequenceBlockDescription)
</td>
<td>
#Html.DisplayFor(modelItem => item.SequenceBlockRequired)
</td>
<td>
#Html.DisplayFor(modelItem => item.SequenceBlockTimingMethod)
</td>
<td>
#Html.DisplayFor(modelItem => item.Duration)
</td>
<td>
#Html.DisplayFor(modelItem => item.StartDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.EndDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.ClerkshipModel)
</td>
<td>
#Html.ActionLink("Edit", "CI_SequenceBlocks_Edit_Form_Handler", new { id = item.SequenceBlockID, value = "Edit_SequenceBlock_ID", inInstitutionProgramID = item.InstitutionProgramID }) |
#Html.ActionLink("Maintain", "CI_SequenceBlocks_Edit_Form_Handler", new { id = item.SequenceBlockID, value = "Maintain_SequenceBlock_ID", inInstitutionProgramID = item.InstitutionProgramID })
</td>
</tr>
}
</table>
#if (ViewData["SelectedInstitutionProgram"].ToString() != "0")
{
<div class="text-center" >
<ul class="pagination">
#for (var i = 1; i <= ViewBag.SearchMetaData.SearchNumberOfPages; i++)
{
if (ViewBag.SearchMetaData.SearchCurrentPage == #i)
{
<li class="active"> #Html.ActionLink(#i.ToString(), "CI_SequenceBlocks_Pager_Form_Handler", new { id = #i, value = ViewBag.SearchMetaData.SearchString, inInstitutionProgramID = ViewData["SelectedInstitutionProgram"].ToString() },null)</li>
}
else
{
<li> #Html.ActionLink(#i.ToString(), "CI_SequenceBlocks_Pager_Form_Handler", "Home", new { id = #i, value = ViewBag.SearchMetaData.SearchString, inInstitutionProgramID = ViewData["SelectedInstitutionProgram"].ToString() },null)</li>
}
}
</ul>
</div>
}
#using (Html.BeginForm("CI_SequenceBlocks_AddSequenceBlock", "Home", FormMethod.Post, new { id = "submitForm" }))
{
if (ViewData["SelectedInstitutionProgram"].ToString() != "0")
{
<table class="table">
<tr>
<td>
#Html.Hidden("HidInstitutionProgram", ViewData["SelectedInstitutionProgram"].ToString())
</td>
</tr>
<tr>
<td>Add Sequence Block:</td>
<td> <input type="submit" value="Add Sequence Block" class="btn btn-sm" /> </td>
</tr>
</table>
}
}
____________NEW UPDATE____________
Found the issue:
I changed RedirectToActionPermanent to RedirectToAction. No more problems!
Thanks,
James
I am trying to implement Pagination to my code using PagedList and PagedList.Mvc
The problem I am facing is that I am getting an error
'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in
System.Core.dll but was not handled in user code
Additional information: 'System.Collections.Generic.List'
does not contain a definition for 'ToPagedList'
Following is my code for PJController.cs:
public ActionResult Index(SearchPostedJob objSearchPostedJob, int? page)
{
Result res = null;
try
{
objSearchPostedJob.page = (objSearchPostedJob.page == null ? 1 : objSearchPostedJob.page);
ViewBag.SearchPostedJob = objSearchPostedJob;
res = objPostedJobDAL.GetPostedJobs(ApplicationSession.CurrentUser.RecruiterId);
if (res.Status)
{
page = 1;
ViewBag.Message = "";
}
else
{
ViewBag.Message = Common.GetMessage(res.MessageId, "[Master]", "Keyword");
}
}
catch (Exception ex)
{
Common.WriteLog(ex);
throw ex;
}
var result = res.Results;
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(result.ToPagedList(pageNumber, pageSize));
}
Below is the code for Index.cshtml:
#model PagedList.IPagedList<NOS.SC.PJ>
#using PagedList.Mvc;
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="postjob-form">
#using (Html.BeginForm("Index", "PostedJob", FormMethod.Get))
{
<div class="j_search" style="margin-left:3%;">
<input class="form-control" name="SearchKeyword" id="SearchKeyword" placeholder="Search Keyword" />
</div>
<div class="j_search">
<input id="pinput1" name="JobLocation" class="form-control" type="text" value="#ViewBag.SearchPostedJob.JobLocation" placeholder="Enter a location">
<input id="Latitude" name="Latitude" type="hidden" value="#ViewBag.SearchPostedJob.Latitude">
<input id="Longitude" name="Longitude" type="hidden" value="#ViewBag.SearchPostedJob.Longitude">
</div>
<div class="j_search">
<select class="form-control" name="Experience" id="Experience">
<option value="" selected>Select Experience</option>
#for (int i = 1; i <= 10; i++)
{
<option value="#i" #(ViewBag.SearchPostedJob.Experience == i ? "selected" : "")>#i</option>
}
</select>
</div>
<div class="j_search">
<select class="form-control" name="Salary" id="Salary">
<option value="" selected>Select Salary</option>
#for (int i = 1; i <= 10; i++)
{
<option value="#i" #(ViewBag.SearchPostedJob.Salary == i ? "selected" : "")>#i</option>
}
</select>
</div>
<div class="add-btn"><a class="btn btn-primary" href="~/PostedJob/Save?returnUrl=/PostedJob/Index">Add New Opening</a></div>
}
</div>
<div>
<table class="table" id="myTable">
<tr>
<th>
#Html.DisplayNameFor(model => model[0].JobTitle)
</th>
<th>
#Html.DisplayNameFor(model => model[0].JobLocation)
</th>
<th>
#Html.DisplayNameFor(model => model[0].NumberOfPositions)
</th>
<th>
#Html.DisplayNameFor(model => model[0].ValidFrom)
</th>
<th>
#Html.DisplayNameFor(model => model[0].ValidTo)<br />
</th>
<th>
#Html.DisplayNameFor(model => model[0].JobReference)
</th>
<th>
#Html.DisplayNameFor(model => model[0].Status)
</th>
<th>
Application
</th>
<th>
CloneJob
</th>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.JobTitle)
</td>
<td>
#Html.DisplayFor(modelItem => item.JobLocation)
</td>
<td>
#Html.DisplayFor(modelItem => item.NumberOfPositions)
</td>
<td>
#Html.DisplayFor(modelItem => item.ValidFrom)
</td>
<td>
#Html.DisplayFor(modelItem => item.ValidTo)<br />
#* #Html.ActionLink("Delete Resume", "DeleteResume", new { ResumeId = Model.ResumeId, returnUrl = "/Nurse/ProfileView" }, new { #class = "btnViewJobDetails" })*#
#if (!item.IsExtendJob)
{
#Html.ActionLink("ExtendJob", "ExtendJob", new { PostedJobId = item.PostedJobId, IsExtendJob = item.IsExtendJob, returnUrl = "/PostedJob/Index" }, new { #class = "btnViewJobDetails" })
}
else
{
<span class="pull-right" style="font-weight:bold; color:red;">JobExtended</span>
}
</td>
<td>
#Html.DisplayFor(modelItem => item.JobReference)
</td>
<td>
#Html.DisplayFor(modelItem => item.Status)
</td>
<td>
#Html.ActionLink("Applied(" + item.AppliedCnt + ")", "JobView", new { PostedJobId = item.PostedJobId, returnUrl = "/PostedJob/Index" }, new { #class = "btnViewJobDetails" })
</td>
<td>
#Html.ActionLink("JobClone", "CloneJob", new { PostedJobId = item.PostedJobId, returnUrl = "/PostedJob/Index" }, new { #class = "btnViewJobDetails" })
</td>
</tr>
}
</table>
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
</div>
#section Scripts
{
#Scripts.Render("~/bundles/jqueryui")
#Styles.Render("~/Content/themes/base/css")
#Scripts.Render("~/bundles/jqueryval")
<script>
function initMap() {
var input = document.getElementById('pinput1');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.addListener('place_changed', function () {
var place = autocomplete.getPlace();
console.log(JSON.stringify(place));
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
var latlong = JSON.parse(JSON.stringify(place.geometry.location));
document.getElementById('Latitude').value = latlong.lat;
document.getElementById('Longitude').value = latlong.lng;
});
}
initMap();
</script>
<script>
$(document).ready(function () {
$("#SearchKeyword").on("keyup", function () {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
<script>
$(document).ready(function () {
$("#pinput1").on("keyup", function () {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
}
Try using this:
public ActionResult Index(FilterPostedJob objFilterPostedJob, int? page)
{
Result res = null;
try
{
objFilterPostedJob.CreatedBy = ApplicationSession.CurrentUser.RecruiterId;
objFilterPostedJob.page = (objFilterPostedJob.page == null ? 1 : objFilterPostedJob.page);
ViewBag.SearchPostedJob = objFilterPostedJob;
res = objPostedJobDAL.GetPostedJobs(objFilterPostedJob);
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(((List<PostedJob>)res.Results).ToPagedList(pageNumber, pageSize));
}
catch (Exception ex)
{
Common.WriteLog(ex);
throw ex;
}
}
Using ToPagedList is an added advantage as all you need to do is to pass the PageNumber and PageSize
Greetings I have developed an ASP.NET MVC 5 application. I'm using pagination, it works but when I want to call a query that I wrote I get the error:
Additional information: Object reference not set to an instance of an object.
I think its a problem on routing but I can't figure it out.
Here is my controller:
public ActionResult Index(string searchString, int? omonimipage, int? id, int? courseID, int? idcom, int? elencoimo, int? elecoimobi, int? elencoinsta, int? page)
{
int elencoomoninumber = (omonimipage ?? 1);
var viewmodel = new mainview();
viewmodel.elencoomonimi = db.ElencoOmonimis
.Include(s => s.ElencoProvinces)
.Include(s => s.ElencoProvinces.Select(r => r.ElencoImmobiliPerDiritti_E_Quote))
.Include(s => s.ElencoProvinces.Select(r => r.ElencoComunis))
.Include(s => s.ElencoProvinces.Select(r => r.ElencoImmobiliPerDiritti_E_Quote.Select(q => q.ElencoIntestatis)))
.OrderBy(i => i.Id).ToPagedList(elencoomoninumber,6);
if (id != null)
{
ViewBag.elencoprovinceID = id.Value;
viewmodel.elencoprovince = viewmodel.elencoomonimi.Where(
i => i.Id == id.Value).SingleOrDefault().ElencoProvinces;
}
if (idcom != null)
{
ViewBag.ElencoImmobiliperID = idcom.Value;
viewmodel.elencointestati = viewmodel.elencoimobili.Where(
r => r.Id == idcom.Value).Single().ElencoIntestatis;
}
if (elencoimo != null)
{
ViewBag.elecomuniID = elencoimo.Value;
viewmodel.elencocomuni = viewmodel.elencoprovince.Where(
r => r.Id == elencoimo.Value).Single().ElencoComunis;
}
if (elecoimobi != null)
{
ViewBag.ElencoimobID = elecoimobi.Value;
viewmodel.elencoimobili = viewmodel.elencoprovince.Where(
q => q.Id == elecoimobi.Value).Single().ElencoImmobiliPerDiritti_E_Quote;
}
if (elencoinsta != null)
{
ViewBag.ElencoInstatiID = elencoinsta.Value;
viewmodel.elencointestati = viewmodel.elencointestati = db.ElencoImmobiliPerDiritti_E_Quote.Where(
e => e.Id == elencoinsta.Value).Single(i =>i.Id == elencoinsta.Value).ElencoIntestatis;
}
return View(viewmodel);
}
and here is my view:
#model automa0._1.Models.mainview
#using PagedList.Mvc;
#{
ViewBag.Title = "Index";
}
Dashboard
#using (Html.BeginForm())
{
#Html.TextBox("SearchString") <br />
<input type="submit" value="Filter" />
}
<div id="content">
<table class="table">
<tr>
<th>
Nome
</th>
<th>
Cognome
</th>
<th>
Data Di Nascita
</th>
<th>
Codice Fiscale
</th>
<th></th>
</tr>
#foreach (var item in Model.elencoomonimi)
{
string selectedRow = "";
if (item.Id == ViewBag.elencoomonimiID)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.DisplayFor(modelItem => item.CognomeCercato)
</td>
<td>
#Html.DisplayFor(modelItem => item.NomeCercato)
</td>
<td>
#Html.DisplayFor(modelItem => item.Cognome)
</td>
<td>
#Html.DisplayFor(modelItem => item.DataDiNascita)
</td>
<td>
#Html.DisplayFor(modelItem => item.CodiceFiscale)
</td>
<td>
#Html.ActionLink("Provinca", "Index", new { id = item.Id }) |
</td>
</tr>
}
</div>
</>
<div id="contentPager">
Page #(Model.elencoomonimi.PageCount < Model.elencoomonimi.PageNumber ? 0 : Model.elencoomonimi.PageNumber) of #Model.elencoomonimi.PageCount
#Html.PagedListPager(Model.elencoomonimi, page => Url.Action("Index", new { omonimipage = page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
</div>
</table>
#if (Model.elencoprovince != null)
{
<h3>Provinca</h3>
<table class="table">
<tr>
<th></th>
<th>Provincia</th>
<th>Terreni</th>
<th>Fabbricati</th>
</tr>
#foreach (var item in Model.elencoprovince)
{
string selectedRow = "";
if (item.Id == ViewBag.elencoprovinceID)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.ActionLink("Select", "Index", new { elecoimobi = item.Id })
</td>
<td>
#item.Provincia
</td>
<td>
#item.Terreni
</td>
<td>
#item.Fabbricati
</td>
#if (item.ElencoImmobiliPerDiritti_E_Quote != null)
{
#item.ElencoImmobiliPerDiritti_E_Quote
}
</tr>
}
</table>
}
#if (Model.elencoimobili != null)
{
<h3>elencoimmobiliperditti</h3>
<table class="table">
<tr>
<th></th>
<th>Classe</th>
<th>Consistenza</th>
<th>Foglio</th>
</tr>
#foreach (var item in Model.elencoimobili)
{
string selectedRow = "";
if (item.Id == ViewBag.ElencoImmobiliperID)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.ActionLink("Select", "Index", new { elencoinsta = item.Id })
</td>
<td>
#item.Classe
</td>
<td>
#item.Consistenza
</td>
<td>
#item.Foglio
</td>
</tr>
}
</table>
}
#if (Model.elencointestati != null)
{
<h3>elneco Intestati</h3>
<table class="table">
<tr>
<th>CodiceFiscale</th>
<th>Nominativo</th>
<th>Titolarita</th>
</tr>
#foreach (var item in Model.elencointestati)
{
string selectedRow = "";
if (item.Id == ViewBag.ElencoImmobiliperID)
{
selectedRow = "success";
}
<tr class="#selectedRow">
<td>
#Html.ActionLink("Select", "Index", new { id = item.Id })
</td>
<td>
#item.CodiceFiscale
</td>
<td>
#item.Nominativo
</td>
<td>
#item.Titolarita
</td>
</tr>
}
</table>
}
on default its working but wen i navigate to page 2 the url its: http://localhost:49208/ElencoOmonimis?omonimipage=2
Thank you.
Hi people I have the following JavaScript code in my Show All Games View:
<script>
$('#SearchBox').autocomplete({ source: '/Controller/ShowAllGames' });
</script>
and the following code to function my autocomplete in my ShowAllGames controller:
public ActionResult AutoCompleteGames(string term)
{
var db = new gamezoneDBEntities();
return Json(db.tblGames.Where(games => games.GameName.StartsWith(term)).Select(games => games.GameName), JsonRequestBehavior.AllowGet);
}
I don't know why my autocomplete is not working as I type my information or words in in my database are not appearing. Also the search box that the script is refering to is the following:
#using (Html.BeginForm())
{
<div id="SearchBorder">
<div id="TopSearch">
#Html.TextBox("DisplaySearchResults", "", new { style = "width:420px;" })
<input id="SearchBox" type="submit" value="Search news archives"/>
</div>
</div>
}
I have a serach box and paging enabled all work well just want to know why my auto complete is not working
Thank you
If you require addtional information please ask me i wil provide thanks
EDIT:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PagedList;
using GamesTest.Models;
namespace GamesTest.Controllers
{
public class ShowAllGamesController : Controller
{
//
// GET: /ShowAllGames/
public ActionResult Index(string Ordering, string WordFilter, string DisplaySearchResults, int? CounterForPage)
{
using (var db = new gamezoneDBEntities())
{
ViewBag.Message = TempData["message"];
ViewBag.CurrentSort = Ordering;
ViewBag.NameSortParm = String.IsNullOrEmpty(Ordering) ? "GameName" : "";
ViewBag.DateSortParm = Ordering == "ReleaseYearOfGame" ? "DiscriptionOfGame" : "Date";
{
TempData["DisplaySearchResult"] = DisplaySearchResults;
{
ViewBag.search = DisplaySearchResults;
}
if (Request.HttpMethod == "GET")
{
DisplaySearchResults = WordFilter;
}
else if (DisplaySearchResults == "")
{
ViewData["MyMessage"] = "Nothing Has Been Entered.";
}
else
{
CounterForPage = 1;
}
ViewBag.CurrentFilter = DisplaySearchResults;
var FullDatabaseItem = from b in db.tblGames
select b;
if (!String.IsNullOrEmpty(DisplaySearchResults))
{
FullDatabaseItem = FullDatabaseItem.Where(b => b.GameName.ToUpper().Contains(DisplaySearchResults.ToUpper()));
}
switch (Ordering)
{
case "HeadlineName":
FullDatabaseItem = FullDatabaseItem.OrderBy(b => b.GameName);
break;
case "DatePosted":
FullDatabaseItem = FullDatabaseItem.OrderBy(b => b.ReleaseYear);
break;
case "DiscriptionDate":
FullDatabaseItem = FullDatabaseItem.OrderBy(b => b.ReleaseYear);
break;
default:
FullDatabaseItem = FullDatabaseItem.OrderByDescending(b => b.ReleaseYear);
break;
}
int pageSize = 3;
int pageNumber = (CounterForPage ?? 1);
var PageNumberResults = FullDatabaseItem.ToPagedList(pageNumber, pageSize);
ViewBag.PageNumberResults = FullDatabaseItem.Count();
if (PageNumberResults.Any())
{
return View(PageNumberResults);
}
return View("ErrorView");
}
}
}
public ActionResult AutoCompleteGames()
{
var db = new gamezoneDBEntities();
string term = this.Request.Params["term"].ToString();
return Json(db.tblGames.Where(games => games.GameName.StartsWith(term)).Select(games => games.GameName), JsonRequestBehavior.AllowGet);
}
//
// GET: /ShowAllGames/Details/5
public ViewResult Details(int id)
{
using (var db = new gamezoneDBEntities())
{
tblGame tblgame = db.tblGames.Find(id);
return View(tblgame);
}
}
//
// GET: /ShowAllGames/Create
public ActionResult Create()
{
return View();
}
//
// POST: /ShowAllGames/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /ShowAllGames/Edit/5
public ActionResult Edit(int id)
{
return View();
}
//
// POST: /ShowAllGames/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /ShowAllGames/Delete/5
public ActionResult Delete(int id)
{
return View();
}
//
// POST: /ShowAllGames/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
My View:
#model PagedList.IPagedList<GamesTest.tblGame>
#{
ViewBag.Title = "Index";
}
#*<h2>Index</h2>*#
#using (Html.BeginForm())
{
<div id="SearchBorder">
<div id="TopSearch">
#Html.TextBox("DisplaySearchResults", "", new { style = "width:420px;" })
<input id="SearchBox" type="submit" value="Search news archives"/>
</div>
</div>
}
<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>
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.autocomplete.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.position.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.core.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.widget.js" type="text/javascript"></script>
<p>
#* #Html.ActionLink("Create New", "Create")*#
</p>
<table id = "OverAll">
#* <tr>
<th>
GameID
</th>
<th>
GameName
</th>
<th>
ReleaseYear
</th>
<th>
Cost
</th>
<th>
Description
</th>
<th>
Downloads
</th>
<th>
Image
</th>
<th>
Console
</th>
<th>
UserName
</th>
<th></th>
</tr>*#
#foreach (var item in Model) {
<tr>
#* <td>
#Html.HiddenFor(modelItem => item.GameID)
</td>*#
<td id = "TableLayout1">
<img width="100" height="100"alt="ImageFromDatabase" src='#item.Image' />
</td>
<td id = "TableLayout2">
#*#Html.DisplayFor(modelItem => item.GameName)*#
#Html.ActionLink(item.GameName, "Details", new { id = item.GameID })
</td>
<td id = "TableLayout3">
#Html.DisplayFor(modelItem => item.ReleaseYear)
</td>
<td id = "TableLayout4">
#Html.Raw(item.Description.Substring(0, item.Description.IndexOf(".") + 1))
#* #Html.DisplayFor(modelItem => item.Description)*#
</td>
<td id = "TableLayout5">
#Html.DisplayFor(modelItem => item.Cost)
</td>
<td id = "TableLayout6">
#Html.DisplayFor(modelItem => item.Downloads) #*want this as a link so I can then click on it and show the game downloads*#
</td>
<td id = "TableLayout7">
#Html.DisplayFor(modelItem => item.ConsoleNameIDFK)
</td>
#*<td>
#Html.HiddenFor(modelItem => item.UserName)
</td>*#
#* <td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>*#
</tr>
}
</table>
#*Below is coding for the page count and the number of results found with the serach result displayed*#
<div class="PageCounter">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
of #Model.PageCount
#if (Model.HasPreviousPage)
{
#Html.ActionLink("<<", "Index", new { CounterForPage = 1, Ordering = ViewBag.CurrentSort, WordFilter = ViewBag.WordFilter })
#Html.Raw(" ");
#Html.ActionLink("< Previous Page", "Index", new { CounterForPage = Model.PageNumber - 1, Ordering = ViewBag.CurrentSort, WordFilter = ViewBag.WordFilter })
}
else
{
#:<<
#Html.Raw(" ");
#:< Prev
}
#if (Model.HasNextPage)
{
#Html.ActionLink("Next Page >", "Index", new { CounterForPage = Model.PageNumber + 1, Ordering = ViewBag.CurrentSort, WordFilter = ViewBag.CurrentFilter })
#Html.Raw(" ");
#Html.ActionLink(">>", "Index", new { CounterForPage = Model.PageCount, Ordering = ViewBag.CurrentSort, WordFilter = ViewBag.CurrentFilter })
}
else
{
#:Next>
#Html.Raw(" ")
#:>>
}
#String.Format("Total of {0} results", ViewBag.PageNumberResults)
(For #ViewBag.Search)
#* #if(ViewBag.Message != null)
{
<p>#ViewBag.Message</p>
}
*#
</div>
<script type="text/javascript">
var uvOptions = {};
(function () {
var uv = document.createElement('script'); uv.type = 'text/javascript'; uv.async = true;
uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/ZRhsC1RL1m4gK5megTxxlw.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(uv, s);
})();
</script>
<script type="text/javascript">
$('#DisplaySearchResults').autocomplete({ source: '/Controller/ShowAllGames' });
</script>
One issue is that you are making your button autocomplete instead of your textbox. Change your autocomplete initialization to the following:
$('#DisplaySearchResults').autocomplete({ source: '/Controller/ShowAllGames' });
Besides the issue jrummell pointed out, your source argument doesn't match the name of your action.
<script>
$('#SearchBox').autocomplete({ source: '/ShowAllGames/AutoCompleteGames' });
</script>
I suspect you are getting 404 errors as you type in the search box.
EDIT
Well it doesn't make sense to me that you are not getting 404's, but try this; remove the parameter string term from your action and use
string term = this.Request.Params["term"].ToString();
within your function. If I remember correctly, the model binder will not set that parameter as expected.