[HttpPost]
public ActionResult Charter(List<int> stateIds)
{
try
{
if (!stateIds.Any())
{
return Json("State list is empty", JsonRequestBehavior.AllowGet);
}
var states = new List<CfVersionEntities.Model.State>();
stateIds.ForEach(id =>
{
using (var db = new Storage_cfEntities())
{
var stateList = db.States.Where(i => i.Id == id).ToList();//get names of states with matching id and save in array named
if (!stateList.Any()) return;
var state = stateList[0];
states.Add(state);
}
});
return !states.Any() ? Json(new List<State>(), JsonRequestBehavior.AllowGet) : Json(states, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
return Json(new List<State>(),
JsonRequestBehavior.AllowGet);
}
}
I have a method that accepts values from my jquery scripts which is below, the script works fine and sends the values, the values are received in my method, i have confirmed that. but when i run it i get the error :The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.... I am using the values from my jquery to loop through my database and select rows that have corresponding IDs, i am then sending this result back to another function in my jquery which creates a highchart with the values
This is my View which includes my script.
List Of States
<p>
<h2> #Html.ActionLink("Add A New State", "CreateState")</h2>
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Stations)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Stations)
</td>
<td>
#Html.ActionLink("Update Stations", "UpdateStation", new {id = item.Id})||
<div>
<input type="checkbox" id="#item.Id" value="#item.Id" class="chk" onclick="setChecked(this)"> <label >Add to Chart</label>
</div>
</td>
</tr>
}
</table>
<div id="charts" style="width:100%" height="400px;"></div>
<input type="button" value="Verify Selections" onclick="submit()"/>
<input type="button" value ="View Chart" onclick="location.href='#Url.Action("Charter")'" />
<script type="text/javascript">
var collection = [];
function setChecked(el) {
var id = $(el).attr('id');
if ($(el).is(':checked'))
{
collection.push(id);
} else {
$.each(collection, function (item, index)
{
if (item === id)
{
collection.splice(index, 1);
}
});
}
}
function submit() {
if (collection == null || collection.length < 1) {
alert('please select at least one state.');
return;
}
$.ajax({
type: "POST",
url: '/State/Charter',
data: { stateIds: collection },
dataType: 'application/json',
success: function (response)
{
if (response.length > 0) {
designChart(response);
}
}
});
}
function designChart(response)
{
var names = [];
var stations = [];
$.each(response, function (item) {
if (item.Id > 0) {
names.push(item.Name);
stations.push(item.Stations);
}
});
$("#charts").highcharts({
chart:
{
type: 'line'
},
title: {
text: 'States'
},
xAxis: {
categories: names
},
yAxis:
{
title:
{
text: 'Stations',
categories: stations
}
}
});
}
</script>
Related
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)
I implemente dynamic add and remove column it's working fine if I remove last row but if I remove first index then it's losing all other rows.
But if I use FormCollection Its binding but not as array list
public ActionResult Index()
{
var employee = new Employee();
employee.Skills.Insert(0, new Skill());
return View(employee);
}
.cshtml
<table id="skills-table">
<thead>
<tr>
<th style="width:20px;"> </th>
<th style="width:160px;">Skill</th>
<th style="width:150px;">Level</th>
<th style="width:32px;"> </th>
</tr>
</thead>
<tbody>
#for (var j = 0; j < Model.Skills.Count; j++)
{
<tr valign="top">
<th><span class="rownumber"></span></th>
<td>
#Html.TextBoxFor(model => model.Skills[j].Title, new { #class = "skill-title" })
#Html.ValidationMessageFor(model => model.Skills[j].Title)
</td>
<td>
#Html.DropDownListFor(
model => model.Skills[j].Level,
new SelectList(WebApplication4.MetaModels.SkillLevel.GetSkillLevels(), "Code", "Description", Model.Skills[j].Level),
"-- Select --",
new {#class = "skill-level"}
)
#Html.ValidationMessageFor(model => model.Skills[j].Level)
</td>
<td>
#if (j < Model.Skills.Count - 1)
{
<button type="button" class="remove-row" title="Delete row"> </button>
}
else
{
<button type="button" class="new-row" title="New row"> </button>
}
</td>
</tr>
}
</tbody>
</table>
jQuery:
<script type="text/javascript">
var addRow = function () {
addTableRow($("#skills-table"));
return false;
};
var deleteRow = function (event) {
$(event.target).closest("tr").remove();
return false;
};
function addTableRow(table) {
/* Sources:
http://www.simonbingham.me.uk/index.cfm/main/post/uuid/adding-a-row-to-a-table-containing-form-fields-using-jquery-18
http://stackoverflow.com/questions/5104288/adding-validation-with-mvc-3-jquery-validator-in-execution-time
*/
var $ttc = $(table).find("tbody tr:last");
var $tr = $ttc.clone();
$tr.find("input,select").attr("name", function () { // find name in the cloned row
var parts = this.id.match(/(\D+)_(\d+)__(\D+)$/); // extract parts from id, including index
return parts[1] + "[" + ++parts[2] + "]." + parts[3]; // build new name
}).attr("id", function () { // change id also
var parts = this.id.match(/(\D+)_(\d+)__(\D+)$/); // extract parts
return parts[1] + "_" + ++parts[2] + "__" + parts[3]; // build new id
});
$tr.find("span[data-valmsg-for]").attr("data-valmsg-for", function () { // find validation message
var parts = $(this).attr("data-valmsg-for").match(/(\D+)\[(\d+)]\.(\D+)$/); // extract parts from the referring attribute
return parts[1] + "[" + ++parts[2] + "]." + parts[3]; // build new value
})
$ttc.find(".new-row").attr("class", "remove-row").attr("title", "Delete row").unbind("click").click(deleteRow); // change buttin function
$tr.find(".new-row").click(addRow); // add function to the cloned button
// reset fields in the new row
$tr.find("select").val("");
$tr.find("input[type=text]").val("");
// add cloned row as last row
$(table).find("tbody tr:last").after($tr);
// Find the affected form
var $form = $tr.closest("FORM");
// Unbind existing validation
$form.unbind();
$form.data("validator", null);
// Check document for changes
$.validator.unobtrusive.parse(document);
// We could re-validate with changes
// $form.validate($form.data("unobtrusiveValidation").options);
};
(function ($) {
/* Source:
http://www.johnculviner.com/post/2011/11/16/ClearReset-MVC-3-Form-and-Unobtrusive-jQuery-Client-Validation.aspx
*/
$.fn.resetValidation = function () {
var $form = this.closest('form');
//reset jQuery Validate's internals
$form.validate().resetForm();
//reset unobtrusive validation summary, if it exists
$form.find("[data-valmsg-summary=true]")
.removeClass("validation-summary-errors")
.addClass("validation-summary-valid")
.find("ul").empty();
//reset unobtrusive field level, if it exists
$form.find("[data-valmsg-replace]")
.removeClass("field-validation-error")
.addClass("field-validation-valid")
.empty();
return $form;
};
})(jQuery);
$(function () {
$(".new-row").click(addRow);
$(".remove-row").click(deleteRow);
})
</script>
Controller:
public ActionResult Index(Employee employee, FormCollection abc, string[]dynamic)
{
return View(employee);
}
Here my FormCollection is getting all the data but not as array type
I am newbie in asp.net mvc.
I have 2 cascading dropdownlist and 1 file input on my page.
I made cascading dropdownlists following this tutorial. But when I trying to pass value to controller, there is an error System.ArgumentException, null parameter. I looked up the list of parameters using Firebug, but I can't find value of second dropdown at all.
My controller code is below:
public ActionResult Index()
{
List<SelectListItem> branchNames = new List<SelectListItem>();
FormatModel fmtModel = new FormatModel();
List<branch> branches = db.branch.ToList();
branches.ForEach(x =>
{
branchNames.Add(new SelectListItem { Text = x.name, Value = x.id.ToString() });
}
);
fmtModel.BranchNames = branchNames;
return View(fmtModel);
}
[HttpPost]
public ActionResult GetPaymentSystem(string branchId)
{
int intBranchId;
List<SelectListItem> paymentSystemNames = new List<SelectListItem>();
if (!string.IsNullOrEmpty(branchId))
{
intBranchId = Convert.ToInt32(branchId);
List<paymentSysDTO> paymentSystems =
(from ps in db.paymentSys
join ps_br in db.br_ps_format on ps.id equals ps_br.ps_id
join br in db.branch on ps_br.branch_id equals br.id
where br.id == intBranchId
select new paymentSysDTO
{
id = ps.id,
name = ps.name,
code = ps.code
}
).ToList();
paymentSystems.ForEach(x =>
{
paymentSystemNames.Add(new SelectListItem { Text = x.name, Value = x.id.ToString() });
}
);
}
return Json(paymentSystemNames, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Index(int BranchNames, int PaymentSystemNames, HttpPostedFileBase file)
{
//controller code
}
View code:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<legend>Введите данные:</legend>
<table>
<tr>
<td>
<label>Филиал</label>
</td>
<td>
#Html.DropDownListFor(x => x.BranchNames, Model.BranchNames, "Выбрать", new { id = "ddlBranch" })
</td>
</tr>
<tr>
<td>
<label>Платежная система/Банк</label>
</td>
<td id="PaymentSystem">
#Html.DropDownListFor(x => x.PaymentSystemNames, new List<SelectListItem>(), "Выбрать", new { #id = "ddlPaymentSystem" })
</td>
</tr>
<tr>
<td>
<input id="InputFile" type="file" name="file" />
</td>
</tr>
<tr>
<td>
<input id="ConvertButton" type="submit" value="Конвертировать" />
</td>
</tr>
</table>
}
#if (null != TempData["msg"])
{
#Html.Raw(TempData["msg"])
}
<script type="text/javascript">
$(function () {
$('#ddlBranch').change(function () {
$.ajax({
type: 'POST',
url: "/Home/GetPaymentSystem",
data: { branchID: $('#ddlBranch').val() },
datatype: "json",
traditional: true,
success: function (data) {
var paymentSystem = "<select id='ddlPaymentSystem'>";
paymentSystem = paymentSystem + '<option value ="">Select</option>';
for (var i = 0; i < data.length; i++)
{
paymentSystem = paymentSystem + '<option value=' + data[i].Value + '>' + data[i].Text + '</option>';
}
paymentSystem = paymentSystem + '</select>';
$('#PaymentSystem').html(paymentSystem);
}
cas
});
});
});
</script>
Sorry for my English and thanks for ur help.
I got an issue with my Ajax. When I clicked on the Remove From Cart, The ajax seems not rendering anything. Any hint? Here is my code:
Index.cshtml
#model Tp1WebStore3.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Shopping Cart";
}
<script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('.RemoveLink').click(function () {
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
});
return false;
});
});
</script>
<h3>
<em>Details</em> du panier:
</h3>
<p class="button">
#Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")
</p>
<div id="update-message">
</div>
<table>
<tr>
<th>
Produit
</th>
<th>
Prix (unitaire)
</th>
<th>
Quantite
</th>
<th></th>
</tr>
#foreach (var item in Model.CartItems)
{
<tr id="row-#item.ProduitId">
<td>
#Html.ActionLink(item.Produit.Description,"Details", "Panier", new { id =
item.ProduitId }, null)
</td>
<td>
#item.Produit.Prix
</td>
<td id="item-count-#item.ProduitId">
#item.Quantite
</td>
<td>
Remove From Cart
</td>
</tr>
}
<tr>
<td>
Total
</td>
<td></td>
<td></td>
<td id="cart-total">
#Model.CartTotal
</td>
</tr>
</table>
PanierController.cs
// AJAX: /ShoppingCart/RemoveFromCart/5
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the album to display confirmation
string produitDescription = dbProduit.Paniers
.Single(item => item.PanierId == id).Produit.Description;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = Server.HtmlEncode(produitDescription) +
" has been removed from your shopping cart.",
CartTotal = cart.GetTotal(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
return Json(results);
ShoppingCart.cs
public int RemoveFromCart(int id)
{
// Get the cart
var cartItem = db.Paniers.Single(
cart => cart.CartId == ShoppingCartId
&& cart.ProduitId == id);
int itemCount = 0;
if (cartItem != null)
{
if (cartItem.Quantite > 1)
{
cartItem.Quantite--;
itemCount = cartItem.Quantite;
}
else
{
db.Paniers.Remove(cartItem);
}
// Save changes
db.SaveChanges();
}
return itemCount;
Here is the Chrome output PF12 for the network tab
Change:
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
To:
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
type: 'POST',
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
}
Another option, although not recommended is to remove the [HttpPost] from the top of your controller. This will raise other issues for you, as the recommended way to send data using ajax is 'POST'
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.