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.
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 am creating an MVC application and I am trying to display data on my table based on the selected values for multiple dropdowns once a button is clicked. I think I am assigning all the values in my code but I am new to coding so I am not sure if I am missing something.
This is my view
#model IgnitionHub2._0.Models.Car
#{
ViewBag.Title = "Car Search Page";
}
<h2>Cars</h2>
<div class="center-div">
<div class="form-inline">
#Html.DropDownListFor(model => model.CarLotID, new SelectList(Model.CarLotList, "CarLotID", "LotName"), "Select Car Lot", new { #class = "form-control" })
#Html.DropDownListFor(model => model.Model.MakeID, new SelectList(Model.MakeList, "MakeID", "Name"), "Select Make", new { #class = "form-control" })
#Html.DropDownListFor(model => model.ModelID, new SelectList(Model.ModelList, "ModelID", "Name"), "Select Model", new { #class = "form-control" })
<button id="search">Search</button>
</div>
</div>
<div id="searchResults">
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
$(document).ready(
function () {
var makeUrl = '#Url.Action("GetCarDetails")';
var models = $('#ModelID')
$('#Model_MakeID').change(function () {
models.empty();
$.getJSON(makeUrl, { MakeID: $(this).val() },function(data){
if (!data) {
return;
}
models.append($('<option></option>').val('').text('Please select'));
$.each(data, function(index, item) {
models.append($('<option></option>').val(item.Value).text(item.Name));
});
});
})
})
$(document).ready(function () {
var url = '#Url.Action("DisplaySearchResults","Car")';
$('#search').click(function () {
var carLotID = $('#CarLotID').val();
var makeID = $('#Model_MakeID').val();
var modelID = $('#ModelID').val();
alert(modelID);
$('#searchResults').load(url, { CarLotID: carLotID, MakeID: makeID, ModelID: modelID });
})
})
This is my Partial view
#model IEnumerable<IgnitionHub2._0.Models.Car>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Year)
</th>
<th>
#Html.DisplayNameFor(model => model.Color)
</th>
<th>
#Html.DisplayNameFor(model => model.Mileage)
</th>
<th>
#Html.DisplayNameFor(model => model.BodyType)
</th>
<th>
#Html.DisplayNameFor(model => model.Drive)
</th>
<th>
#Html.DisplayNameFor(model => model.Available)
</th>
<th>
#Html.DisplayNameFor(model => model.Model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.CarLot.LotName)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Year)
</td>
<td>
#Html.DisplayFor(modelItem => item.Color)
</td>
<td>
#Html.DisplayFor(modelItem => item.Mileage)
</td>
<td>
#Html.DisplayFor(modelItem => item.BodyType)
</td>
<td>
#Html.DisplayFor(modelItem => item.Drive)
</td>
<td>
#Html.DisplayFor(modelItem => item.Available)
</td>
<td>
#Html.DisplayFor(modelItem => item.Model.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.CarLot.LotName)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.CarID }) |
#Html.ActionLink("Details", "Details", new { id=item.CarID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.CarID })
</td>
</tr>
}
</table>
And this is my controller
public ActionResult Index()
{
var cars = db.Cars.Include(c => c.Model).Include(c => c.CarLot);
var makeList = db.Makes.ToList();
var modelList = db.Models.ToList();
var carLotList = db.CarLots.ToList();
var ViewModel = new Car
{
CarList = cars,
MakeList = makeList,
ModelList= modelList,
CarLotList = carLotList
};
return View(ViewModel);
}
public ActionResult DisplaySearchResults(int CarLotID, int MakeID, int ModelID)
{
var model = db.Cars.Where(c => c.Model.MakeID == MakeID && c.ModelID == ModelID &&
c.CarLotID == CarLotID).ToList();// build list based on parameter searchText
return PartialView("_Index", model);
}
public ActionResult _Index()
{
var cars = new List<Car>();
return PartialView(cars);
}
public JsonResult GetCarDetails(int MakeID)
{
db.Configuration.ProxyCreationEnabled = false;
var data = GetModels(MakeID).ToList();
//data = data.Where(x => x.Model.MakeID == MakeID).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
Please Help! Thank you in advance!
According to the documentation, https://api.jquery.com/load/, .load() uses POST http request if you're passing an object as parameter, which you are doing right now with;
// {CarLotID:carLotID,MakeID:makeID,ModelID:modelID} is an object
$('#searchResults').load(url, { CarLotID: carLotID, MakeID: makeID, ModelID: modelID });
OPTION 1-- Since you didn't write your action method to be POST, you could just configure your .load() to use GET.
Use the code below for .load();
$('#searchResults').load(url+"?CarLotID="+carLotID+"&MakeID="+makeID+"&ModelID="+modelID);
then change
#Html.DropDownListFor(model => model.ModelID, new SelectList(Model.ModelList, "ModelID", "Name"), "Select Model", new { #id="ModelID", #class = "form-control" })
In your loop to refill the dropdown, use this instead;
$.each(data, function(index, item) {
models.append($('<option value="+item.MakeID+"></option>').text(item.Name));
});
updated script:
$('#Model_MakeID').change(function(){
models.empty();
$.getJSON(makeUrl, { MakeID: $(this).val() }, function(data){
if (!data) {
return;
}
models.append($('<option></option>').val('').text('Please select'));
// update this
$.each(data, function(index, item) {
models.append($('<option value="+item.Value+"></option>').text(item.Name));
});
});
});
OR OPTION 2-- just add [HttpPOST] attribute to your controller action.
[HttpPost] // add this
public ActionResult DisplaySearchResults(int CarLotID, int MakeID, int ModelID)
{
...
}
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
I am displaying page links with the help of PagedList in ASP.net MVC. But the issue is if there are 100 pages then all links show at the same time but i want to show 10 links at a time. How can it be achieved. Please Help. Thanks.. Below is the working Code.
Index.cshtml
#model PagedList.IPagedList<MvcPagingList.Models.Employee>
#{
ViewBag.Title = "Employees";
}
<link href="#Url.Content("~/bootstrap/css/bootstrap.min.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("~/bootstrap/css/bootstrap.css")" rel="stylesheet" type="text/css" />
<h2>
Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
#using (Html.BeginForm())
{
<p>
Search By Name : #Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
<input type="submit" value="Search" /></p>
}
<table>
<tr>
<th>
#Html.Label("Last Name")
</th>
<th>
#Html.Label("First Name")
</th>
<th>
#Html.Label("Department ID")
</th>
<th>
#Html.ActionLink("Salery", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.DepartmentID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Salary)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.EmployeeID }) |
#Html.ActionLink("Details", "Details", new { id = item.EmployeeID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.EmployeeID })
</td>
</tr>
}
</table>
<div class="pagination pagination-right">
<ul>
<li>
#for (int p = 1; p <= Model.PageCount; p++)
{
#p
}
</li>
</ul>
</div>
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcPagingList.Models;
using PagedList;
namespace MvcPagingList.Controllers
{
public class HomeController : Controller
{
EmployeeEntities dbEntities = new EmployeeEntities();
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page)
{
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "Salery desc" : "";
//ViewBag.DateSortParm = sortOrder == "HireDate" ? "HireDate desc" : "HireDate";
if (Request.HttpMethod == "GET")
{
searchString = currentFilter;
}
else
{
page = 1;
}
ViewBag.CurrentFilter = searchString;
var employees = from s in dbEntities.Employees
select s;
if (!String.IsNullOrEmpty(searchString))
{
employees = employees.Where(s => s.LastName.ToUpper().Contains(searchString.ToUpper())
|| s.FirstName.ToUpper().Contains(searchString.ToUpper()));
}
switch (sortOrder)
{
case "Salery desc":
employees = employees.OrderByDescending(s => s.LastName);
break;
default:
employees = employees.OrderBy(s => s.LastName);
break;
}
int pageSize = 3;
int pageNumber = (page ?? 1);
return View(employees.ToPagedList(pageNumber, pageSize));
}
}
}
I faced the same issue & solved it by studying the following Code :-
http://msdn.microsoft.com/en-us/magazine/gg650669.aspx
You will have to use webgrid for this.
http://www.w3schools.com/aspnet/showfile_c.asp?filename=try_webpages_cs_004
I try to add my files into DropDownList, all my files with the relevant property already return by the controller:
// GET: /WebMail/
public ActionResult Index()
{
var fileNameList = db.Captures.ToList().Where(x => x.robotFamily == "WebMail");
//return View(db.Captures.ToList().Where(x => x.robotFamily == "WebMail"));
ViewBag.Files = fileNameList;
return View();
}
Index.cshtml
#model IEnumerable<AutomationCapturesMVC.Models.Capture>
#{
//ViewBag.Title = "Index";
}
<table class="table">
<tr>
<th style="font-size: 20px">
#Html.DisplayNameFor(model => model.fileName)
</th>
<th></th>
</tr>
#Html.DropDownList("Id", (IEnumerable<AutomationCapturesMVC.Models.Capture>)ViewBag.Files, new { id = "WebMail", #class = "btn dropdown-toggle" })
#foreach (var item in Model)
{
<tr>
<td style="font-size: 15px">
#Html.DisplayFor(modelItem => item.fileName)
</td>
<td>
#Html.ActionLink("File Details", "Details", new { id = item.id })
</td>
</tr>
}
</table>
this is my page error:
http://s21.postimg.org/983eokpfq/1231231313.jpg
How about the following?
In controller
public ActionResult Index()
{
var fileNames = GetDatabaseFileNames();
var fileNameList = fileNames.Select(d => new SelectListItem { Text = d.FileName, Value = d.FileName.ToString() }).ToList();
ViewBag.Files = fileNameList;
return View();
}
In View
#Html.DropDownList("DatabaseFiles", (IEnumerable<SelectListItem>)ViewBag.Files, new { id = "DatabaseFiles", #class = "btn dropdown-toggle" })