i can not use jquery select2 with json - c#

i MVC4 and i want to add a select box that retrieve data (Product code) from my database the problem is that i have a message from select2.js telling select2 touppercase of undefined.
*all the JS file are uploaded.
here is my Jquery function:
<script>
$(document).ready(function () {
$('#Product_cd').select2({
minimumInputLength: 2,
ajax: {
url: '#Url.Action("AutoComplete")',
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
});
</script>
here is my controller AutoComplete
public JsonResult AutoComplete(string q)
{
Mydb db = new Mydb();
var Code = from c in db.Products
where c.Product_code.Contains(q)
select c.Product_code;
var result = Code.ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
}
and here is part of the view:
<div class="col-md-2">
<div>#Html.DisplayNameFor(x => x.Product_cd )</div>
<div> #Html.TextBoxFor(x => x.Product_cd)<i class="fa fa-search"></i></div>
</div>
can any one tell me what is the problem

Related

MVC: 404 not found in ajax

I am showing a number of flights in a view. I have created a button for every flight. On clicking this button I am getting the details of a single flight shown in the view.
here is my view code:
foreach (var item in Model)
{
<div class="toFrom">
<h3 id="FCity_#item.FlightID">#item.FromCity </h3>
<span><i class="fa mx-4 fa-plane"></i></span>
<h3 id="TCity_#item.FlightID">#item.ToCity</h3>
</div>
<div class="info d-flex">
<p class="me-2 " id="DDate_#item.FlightID">#item.DepartureDate.ToShortDateString()</p>
<p class="me-2" id="DTime_#item.FlightID">#item.DepartureTime.ToShortTimeString()</p>
<p class="me-2 " id="ATime_#item.FlightID">#item.ArrivalTime.ToShortTimeString()</p>
<select id="CFare_#item.Fare" class="form-control me-2">
#foreach (var re in ddlcabin)
{
<option value="#re.Fare">#re.CabinName (#re.Fare)</option>
}
</select>
<button class="form-control btn btn-primary" onclick="Save(#item.FlightID,#item.Fare)">select </button>
</div>
}
Now I want to get these values using and pass them to an action method without using a form in the view.
here is my js code:
function Save(id, fare) {
var fct = $("#FCity_" + id).text();
var tct = $("#TCity_" + id).text();
var ddt = $("#DDate_" + id).text();
var dt = $("#DTime_" + id).text();
var at = $("#ATime_" + id).text();
var cf = $("#CFare_" + fare).val();
$.ajax({
method: 'GET',
url: 'Flights/ReserveFlight',
data: { FromCity: fct, ToCity: tct, DepDate: ddt, DepTime: dt, ArrTime: at, CabinFare: cf },
success: function (data) {
console.log("data is inserted")
},
error: function (err) {
console.log(err)
}
});
}
when I click the save button it shows an error in the browser console and doesn't hit the debugger applied to the action method
here is my action method:
public ActionResult ReserveFlight(string FromCity, string ToCity, DateTime DepDate, DateTime DepTime, DateTime ArrTime, int CabinFare)
{
return View();
}
here is the error:
GET
http://localhost:64480/Flights/Flights/ReserveFlight?FromCity=Islamabd%20&ToCity=Karachi&DepDate=5%2F20%2F2022&DepTime=8%3A30%20AM&ArrTime=12%3A00%20AM&CabinFare=4500 404 (Not Found)
Modify the URL in ajax as:
$.ajax({
method: 'GET',
url: '/Flights/ReserveFlight',
data: { FromCity: fct, ToCity: tct, DepDate: ddt, DepTime: dt, ArrTime: at, CabinFare: cf },
success: function (data) {
console.log("data is inserted")
},
error: function (err) {
console.log(err)
}
});
Or work with UrlHelper.
$.ajax({
method: 'GET',
url: '#Url.Action("Flights", "ReserveFlight")',
data: { FromCity: fct, ToCity: tct, DepDate: ddt, DepTime: dt, ArrTime: at, CabinFare: cf },
success: function (data) {
console.log("data is inserted")
},
error: function (err) {
console.log(err)
}
});
Reference: Action(String, String) | UriHelper.Action() Method

Need to simulate an #Html.action() on a button click

I'm having some issues with updating a partial view in my index view. Basically, based on a click, I would like to have updated information.
//controller
public ActionResult Index()
{
var filteredObservations = getFilteredObservationSessions().ToList();
var observationManagementVm = new ObservationManagementVM(filteredObservations);
return View(observationManagementVm);
}
public ActionResult indexPagedSummaries(int? page, List<ObservationSessionModel> data)
{
var alreadyFilteredObservations = data;
int PageSize = 10;
int PageNumber = (page ?? 1);
return PartialView(alreadyFilteredObservations.ToPagedList(PageNumber, PageSize));
}
My main view
//index.cshtml
#model AF.Web.ViewModels.ObservationManagementVM
....
<div id="testsim">
#Html.Action("indexPagedSummaries", new { data = Model.ObservationSessions })
</div>
<input id="new-view" value="Sessions" type="button" />
<script>
$("#new-view").click(function() {
$.ajax({
type: "GET",
data: { data: "#Model.FeedBackSessions" },
url: '#Url.Action("indexPagedSummaries")',
cache: false,
async: true,
success: function (result) {
console.log(result);
$('#testsim').html(result);
$('#testsim').show();
}
});
});
</script>
....
And my partial view
//indexPagedSummaries.cshtml
#model PagedList.IPagedList<AF.Services.Observations.ObservationSessionModel>
#using (Html.BeginForm("indexPagedSummaries"))
{
<ol class="vList vList_md js-filterItems">
#foreach (var item in Model)
{
#Html.DisplayFor(modelItem => item)
}
</ol>
<div>
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index",
new { page }))
</div>
}
Html.Action() returns what I want perfectly, but it doesn't seem to be able to be triggered by a button click.
So, I'm not getting any errors, but the url doesn't give any data back. When I try to run the Observation/indexPagedSummary url without passing in data, I get a System.ArgumentNullException error, so I'm assuming that something is being transferred to the view model. Any help would be so appreciated.
Have not run your code but I believe it is because you are not sending the data along with the #Url.Action
Main View:
//index.cshtml
#model AF.Web.ViewModels.ObservationManagementVM
....
<div id="testsim">
#Html.Action("indexPagedSummaries", new { data = Model.ObservationSessions })
</div>
<input id="new-view" value="Sessions" type="button" />
<script>
$("#new-view").click(function() {
$.ajax({
type: "GET",
data: { data: "#Model.FeedBackSessions" },
url: '#Url.Action("indexPagedSummaries", "[Controller Name]", new { data = Model.ObservationSessions})',
cache: false,
async: true,
success: function (result) {
console.log(result);
$('#testsim').html(result);
$('#testsim').show();
}
});
});
</script>
If that doesn't help I have had issues when I have had a content-type mismatch or a datatype mismatch. You may need to add those to you ajax request.
Change your ajax data line to this:
data: { data: JSON.stringify(#Model.FeedBackSessions) },
You may also need to add these lines to the ajax:
dataType: 'json',
contentType: 'application/json; charset=utf-8',
You can see in one of your comments above that the current URL is being formed with a description of the List Object, rather than the contents of it:
http://localhost:60985/Observation/indexPagedSummaries?data=System.Collections.Generic.List%601%5BAF.Services.Observations.ObservationSessionModel%5D&data=System.Collections.Generic.List%601%5BAF.Services.Observations.ObservationSessionModel%5D&_=1482453264080
I'm not sure if there's a better way, but you may even have to manually get the model data into Javascript before posting it.
eg:
<script>
var temp = [];
#foreach (var item in Model.FeedBackSessions){
#:temp.push(#item);
}
</script>
and then data: { data: JSON.stringify(temp) },

Problems Cascading dropdownlist, generated dropdown isn't posting selected value to server

Here is my view in image
The code is working fine, but...
When i submit the form, it only sends the value of first dropdownlist (I checked on browser network received arguments), also when i view the page source it doesn't show the generated options that I generated using ajax function.
Here is my Code
Action that generate my first dropdownList
public ActionResult TwoDropDownList()
{
HotelContext H = new HotelContext();
ViewBag.DropDownListOne = new SelectList(H.Continent.ToList(), "Id", "Name");
return View();
}
Action that return json of second dropdownlist data
[HttpPost]
public JsonResult UpdateCountryDropDownList(int ContinentId)
{
HotelContext H = new HotelContext();
List<SelectListItem> CountryNames = new List<SelectListItem>();
List<Country> Co = H.Country.Where(x => x.ContinentId == ContinentId).ToList();
Co.ForEach(x =>
{
CountryNames.Add(new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
});
return Json(CountryNames , JsonRequestBehavior.AllowGet);
}
My Ajax call
#model Hotel.Models.Continent
<script>
$(document).ready(function () {
$("#Name").change(function () {
var ContinentoId = $(this).val();
$.ajax({
type: "POST",
dataType: "json",
data: { ContinentId: ContinentoId },
url: '#Url.Action("UpdateCountryDropDownList","Home")',
success: function (result) {
var Country = "<select id='ddlCountry'>";
Country = Country + '<option value="">--Select--</option>';
for (var i = 0; i < result.length; i++) {
Country = Country + '<option value=' + result[i].Value + '>' + result[i].Text + '</option>';
}
Country = Country + '</select>';
$('#Countries').html(Country);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(arguments)
}
});
});
})
</script>
My View
#using(Html.BeginForm()){
SelectList se = ViewBag.DropDownListOne;
#Html.DropDownListFor(x=>x.Name,se,"--Select--")
<div id ="Countries">
#Html.DropDownList("ddlCountry",new List<SelectListItem>(),"--Select--")
</div>
<input type="submit" value="submit" style="margin-top:100px;" />
}
HTTPPost Action
[HttpPost]
public string TwoDropDownList(string Name, string ddlCountry)
{
if (string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(ddlCountry))
{
return ("you must select Both");
}
else
return ("everything is working fine");
}
You already have a <select> element with name="ddlCountry" (generated by #Html.DropDownList("ddlCountry", new List<SelectListItem>(), "--Select--") but in the ajax call, you overwrite it and create a new <select> element without a name attribute (so its value is not posted back.
In the success callback, you should be creating <option> elements and appending them to the existing <select>
success: function (result) {
var country = $('#ddlCountry); // get the existing element
country.empty().append($('<option></option>').val('').text('--Select--'));
$.each(result, function(index, item) {
country.append($('<option></option>').val(item.Value).text(item.Text));
});
}
Side note: Your methods should be returning a collection of anonymous objects, not SelectListItem There is no point sending extra data (the other properties of SelectListItem) across the wire when you don't use them.
I think you are missing the end tag </div> for the <div id ="Countries">.
Try this:
<div id ="Countries">
#Html.DropDownList("ddlCountry",new List<SelectListItem>(),"--Select--")
</div>

ASP.NET MVC4 : Filter search result in same view

I have done searching part for a list in a partialView.
I have multiple partialView in this application as you can see from image.
So my question
Whenever I create search filter for a grid then I have to create another view and partialview to show the success results. How can I show filtered search list within this same partial view and don't need to make a success partialview for that list again?
I've done-
Rendering list from database-
public ActionResult _ProductSearchList() {
List<ProductModel> product;
product = (from u in db.ProductTables
select new ProductModel {
productname = u.ProductName,
productprice = Convert.ToInt32(u.ProductPrice),
productID = u.ProductID,
dateaddproduct = Convert.ToDateTime(u.ProductAddDate)
}).ToList();
return PartialView(product);
}
Searching for records-
<div>
<legend>Prducts</legend>
<input type="text" id="search-products" />
#Html.Action("_ProductSearchList", "LedgerIndex")
</div>
Script for retrieving records-
<script type="text/javascript">
$(function () {
$('#search-products').keyup(function () {
var serachstring = $(this).val();
$.ajax({
url: '/Product/JsonSearchProduct/?stringSearched=' + serachstring,
type: 'get',
datatype: 'json',
success: function (data) {
JSON.stringify(data);
}
});
});
});
</script>
Json result in controller-
public JsonResult JsonSearchProduct(string stringSearched) {
List<ProductModel> product;
product = (from u in db.ProductTables
where u.ProductName.Contains(stringSearched)
select new ProductModel {
productID = u.ProductID,
productname = u.ProductName,
productprice = Convert.ToInt32(u.ProductPrice),
dateaddproduct = Convert.ToDateTime(u.ProductAddDate)
}).ToList();
return Json(product, JsonRequestBehavior.AllowGet);
}
So when I searched String M it retrieves records and showing only records containing M in their name.
Now this filtered result as JSON is what I want to filter in this same partialView without creating extra partialView.
You can let the search method return the same partial view:
public ActionResult JsonSearchProduct(string stringSearched)
{
List<ProductModel> products;
// Search for products...
return PartialView("_ProductSearchList", products);
}
If you wrap the partial view inside a div, you can replace its html with jQuery.
$(function () {
$('#search-products').keyup(function () {
var serachstring = $(this).val();
$.ajax({
url: '/Product/JsonSearchProduct/?stringSearched=' + serachstring,
type: 'get',
datatype: 'json',
success: function (data) {
// data will contain the html of the partial view.
$('div#product-grid').html(data);
}
});
});
});
Note: your Ajax get request can be like this, if you have the JavaScript inside the view:
$.get('#Url.Action("JsonSearchProduct", "Product")',
{
stringSearched: searchstring
},
function (data) {
$('div#product-grid').html(data);
}
});

How to assign drop down list data in this AJAX function?

I want to change the drop down list(ddlSite) when user change the another drop down list(ddlCompany).
So I don't know how to add the new items to ddlsite drop down list.
Ajax Function
function getSite(companyID) {
alert(companyID);
$.ajax({
type: 'POST',
dataType: 'html',
url: '#Url.Action("SiteList", "Site")',
data: ({ ComID: companyID }),
success: function (result) {
alert(result);
$('#SiteList').html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
My view
#Html.DropDownList("ddlCompany", ViewData["AllCompany"] as SelectList, "--Select Item--", new { #onchange = "getSite(this.value);" })
<div id="SiteList">
#Html.Partial("_siteList", SiteList)
</div>
This is my controller
public ActionResult SiteList(int ComID)
{
var siteQuery = from s in db.tblSites
orderby s.SiteName
where s.FKComId == ComID
select s;
IEnumerable<SelectListItem> AllSite = new SelectList(siteQuery, "PKSiteID", "SiteName");
ViewBag.AllSite = siteQuery;
return PartialView("_siteList", siteQuery);
}
My partial view
#model SKG_website.Models.tblSite
#{
ViewBag.Title = "_siteList";
var allSites = ViewBag.AllSite as IEnumerable<SKG_website.Models.tblSite>;
}
<div id="siteList" class="editor-field">
#Html.DropDownListFor(model => model.PKSiteID, new SelectList(allSites, "PKSiteID", "SiteName"))
</div>
I don't know how to assign the sslsit drop down list in the AJAX function. How do I do it?

Categories