search mvc json jquery - c#

I'm having trouble with auto-search when I want to make two values
I want to search the store for product, please guide:
Controller
public JsonResult Search(string pr, string name, string model, string brand, string storename) {
var s = _context.Products.Where(a => a.Name.Contains(pr) || a.Model.Contains(pr) || a.Brands.Name.Contains(pr)).Select(a => new {
name = a.Name, model = a.Model, brand = a.Brands.Name
}).Take(10);
var storen = _context.Stores.Where(a => a.Name.StartsWith(pr)).Select(a => new {
storename = a.Name
});
return Json(new {
s,
storen
}, JsonRequestBehavior.AllowGet);
}
View
$(document).ready(function () {
var kam;
$("#CityName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/search",
type: "POST",
dataType: "json",
data: {
pr: request.term
},
success: function (data) {
response($.map(data, function (item) {
return [{
label: item.name + " " + item.model + " " + item.brand,
value: item.name + " " + item.model + " " + item.brand
}]
}))
}
})
},
messages: {
noResults: "",
results: ""
}
});
})

I think you want to combine both result sets to show into one Autocomplete widget. So for that, try to modify your code to look like this
Controller
public JsonResult Search(string pr) {
var s = _context.Products.Where(a => a.Name.Contains(pr) || a.Model.Contains(pr) || a.Brands.Name.Contains(pr)).Take(10).Select(a => new {
resultItem = a.Name + " " + a.Model + " " + a.Brands.Name
}).ToList();
var storen = _context.Stores.Where(a => a.Name.StartsWith(pr)).Select(a => new {
resultItem = a.Name
}).ToList();
var returnList = s.Concat(storen).ToList();
return Json(new {
returnList
}, JsonRequestBehavior.AllowGet);
}
This way your controller returns only one result set in json format.
View
$(document).ready(function () {
$("#CityName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/Search",
type: "GET",
dataType: "json",
data: {
pr: request.term
},
success: function (data) {
response($.map(data, function (item) {
return [{
label: item.resultItem,
value: item.resultItem
}]
}))
}
})
},
messages: {
noResults: "",
results: ""
}
});
})
Note that I have changed the ajax request type to GET and label and value use the same resultItem field.

Instaed of:
var storen = _context
.Stores
.Where(a => a.Name.StartsWith(pr))
.Select(a => new { storename = a.Name });
Don't you want to use Contains, like in the first query ?
var storen = _context
.Stores
.Where(a => a.Name.Contains(pr))
.Select(a => new { storename = a.Name });

Related

I want to use C# distinc how can I do

I have select2s, I fill these select2 with procedure. I fill select2 by saying return json on the controller side. But repetitive recordings are coming, where can I use DISTINCT for this?
JavaScript
$('#markaSelect').select2({
ajax: {
url: '/Home/MarkaGetir',
data: function (params) {
var query = {
q: params.term,
ModelAd: $('#modelselect').val(),
UreticiAd: $('#ureticiselect').val()
}
return query;
},
dataType: 'json',
type: "POST",
},
placeholder: 'Marka Seçiniz',
allowClear: true
});
Controller
public JsonResult MarkaGetir(string q = "", string MarkaAd = "", string ModelAd = "", string UreticiAd = "")
{
var lst = Vtİslemleri.Mmu(MarkaAd, ModelAd, UreticiAd);
lst.Select(x => x.Marka).Distinct();
return Json(new
{
results = lst.Select(x =>
new
{
id = x.Marka,
text = x.Marka
})
});
}
A short example: There are 4 of the Seat brand models, I want 1 to come when I shoot this.

How to access an array retrieved from controller via AJAX

I call an MVC controller via Java and AJAX. The data goes to the controller, the controller returns a List. How do I access that list? This may seem trivial, but I can't find it anywhere on google or SO. Most of the examples I've found call for using:
...
success: function (r) {
var exemptions = r.d;
...
for (var i = 0; i < exemptions.length; i++){
ddlist.appent('<option>' + exemptions[i] + '</option>');
....
}
That method, however, results in this error:
Uncaught TypeError: Cannot read property 'length' of undefined
at Object.success (6:281)
at u (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at k (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
Controller Method:
public JsonResult GetValidRecords(int year)
{
var items = new List<SelectListItem>();
var Exemptions = model.Permits.Where(m => m.Year == year).OrderBy(m => m.Exemption).OrderBy(m => m.Year).ToList();
foreach (Permit x in Exemptions)
{
items.Insert(items.Count, new SelectListItem { Text = x.Exemption.ToString(), Value = x.Exemption.ToString() });
}
return Json(items, JsonRequestBehavior.AllowGet);
}
The dropdown box:
<text>EXEMPTION RENEWAL FORM</text>
<select id="dd" name="dd" onchange="CallRenewalReport(this.value)">
<option value="">Select Year First</option>
</select>
#Html.DropDownList("ddldate", new SelectList(Model.RYearList, "ID", "Year", "Select a year"), new { #onchange = "GetGoodRecords(this.value)", #AppendDataBoundItems = "False" })
break;
The JavaScript/AJAX query:
<script type="text/javascript">
function GetGoodRecords(val) {
alert(val);
var year = val;
var RootUrl = '#Url.Content("~/")';
$.ajax({
url: RootUrl + "Reports/GetValidRecords",
data: { year: year },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var exemptions = response.d;
var ddlist = $('#dd');
ddlist.empty().append('<option selected="selected" value="0">Select Exemption</option>');
for (var i = 0; i < exemptions.length; i++) {
ddlist.append('<option>' + exemptions[i] + '</option>');
}
}
});
};
</script>
Can anyone spell this out to me in layman's terms?
Regards,
Carthax
Give this a shot in your success function:
success: function (response) {
for (var i = 0; i < response.length; i++) {
var obj = JSON.parse(JSON.stringify(response[i]));
alert(obj.Text);
}
}
This will show an alert of what is contained in each object of the response array.
(In case someone happens upon this question in google)
Based on input from #MikeMarshall, here is the solution that works:
The controller action is correct, but I'm putting it all in one place so you don't have to copy-and-paste from all over the page
public JsonResult GetValidRecords(int year)
{
var items = new List<SelectListItem>();
var Exemptions = model.Permits.Where(m => m.Year == year).OrderBy(m => m.Exemption).OrderBy(m => m.Year).ToList();
foreach (Permit x in Exemptions)
{
items.Insert(items.Count, new SelectListItem { Text = x.Exemption.ToString(), Value = x.Exemption.ToString() });
}
return Json(items, JsonRequestBehavior.AllowGet);
}
The razor code:
<text>EXEMPTION RENEWAL FORM</text>
<select id="dd" name="dd" onchange="CallRenewalReport(this.value)">
<option value="">Select Year First</option>
</select>
#Html.DropDownList("ddldate", new SelectList(Model.RYearList, "ID", "Year", "Select a year"), new { #onchange = "GetRecords(this.value)", #AppendDataBoundItems = "False" })
break;
The script:
<script type="text/javascript">
function GetRecords(val) {
alert(val);
var year = val;
var RootUrl = '#Url.Content("~/")';
$.ajax({
url: RootUrl + "Reports/GetValidRecords",
data: { year: year },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// get the dropdownlist
var ddlist = $('#dd');
// empty the dropdownlist and add "Select Exemption"
ddlist.empty().append('<option selected="selected" value="0">Select Exemption</option>');
// for each value in the response
for (var i = 0; i < response.length; i++) {
// properly query the Value and Text fields in the array
ddlist.append('<option value="' + response[i].Value + '">' + response[i].Text + '</option>');
}
}
});
};
</script>

Displaying a list in a view from data passed from a controller

I'm passing a list in JSON format from my controller, the data from the list is not being displayed in the view for some reason.
Here is the data being passed in controller:
[HttpPost]
public ActionResult GetIndustryCat(string Country)
{ var dataContext = MvcApplication.GetDataContext();
var Location = dataContext.Locations.Single(c => c.Location_Name == Country);
var IndustryCat = dataContext.IndustryCategories.Where(c => c.Location_ID == Location.Location_ID).ToList();
return Json(new {Cat = IndustryCat.Select(c => c.IndustryCategory_Name) });
}
Here is the view:
</select>
<script>
$("#selectindustrycat").hide();
$("select")
.change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$.ajax({
url: "GetIndustryCat",
type: "POST",
data: { Country: str },
success: function (data) {
}
}).done(function (data) {
for (var i = 0; i < data.length; i++) {
$("#selectindustrycat").append('<option value=' + i + '>' + i + '</option>');
}
$("#selectindustrycat").show();
});
});
</script>
The selection option list displays but it has no data in it.
You need change from data to data.Cat
for (var i = 0; i < data.Cat.length; i++) {
$("#selectindustrycat").append('<option value=' + i + '>' + i + '</option>');
}

Add multiple records setting properties using an index

I have a table full of checkboxes, and at the top there's a select all checkbox. Once clicked, I am making an ajax call that passes in a list of invoice_ids as well as the check_run_id of another table. What I'm having difficulty with is setting the property of an object based on the index of the list of invoices. The code will probably explain better. Thanks for any help.
public static void SaveInvoicesForPayment(List<int> invoiceIDs, int checkRunID)
{
using (MiniProfiler.Current.Step("SaveInvoices()"))
using (var context = rempscoDataContext.CreateContext())
{
toSave = invoiceIDs.Where(i => i > 0);
var toDelete = invoiceIDs.Where(i => i < 0).Select(i => -i);
toSave = toSave.Where(i => !toDelete.Contains(i));
var db_invoice_to_update = context.vendor_invoices.Where(si => toDelete.Contains(si.invoice_id));
var db_check_run_details_to_delete = context.check_run_details.Where(crd => crd.check_run_id == checkRunID);
db_invoice_to_update.ToList().ForEach(vi => { vi.check_run_id = null; });
db_check_run_details_to_delete.ToList().ForEach(crd => {
crd.bank_draft_id = null;
crd.is_active = false;
});
var invoice_to_save = context.vendor_invoices.Where(si => toSave.Contains(si.invoice_id)).ToList();
foreach (var crd in invoice_to_save)
{
context.check_run_details.InsertOnSubmit(new check_run_detail
{
invoice_id = crd.invoice_id,
check_run_id = checkRunID,
add_user = Security.CurrentUser,
add_date = DateTime.Now,
edit_user = Security.CurrentUser,
edit_date = DateTime.Now,
invoice_amount = **invoice_to_save[index??],**
is_active = true,
});
}
context.SubmitChanges();
}
}
Here's the ajax call as well just in case:
function doSaveInvoices($parent, checked) {
var $invoiceCheckBoxes = $parent.find('input.invoice[type="checkbox"]');
var checkRunID = $("#checkRunID").val();
var invoiceIDs = [];
if (checked) {
$invoiceCheckBoxes.each(function (i, c) {
var $checkbox = $(this);
invoiceIDs.push($checkbox.attr('invoice_id'));
$checkbox.attr('checked', true);
});
}
else {
$invoiceCheckBoxes.each(function (i, c) {
var $checkbox = $(this);
invoiceIDs.push(-$checkbox.attr('invoice_id'));
$checkbox.attr('checked', false);
});
}
var js = JSON.stringify({ invoiceIDs: invoiceIDs, checkRunID: checkRunID });
$.ajax({
url: './PayInvoicesWS.asmx/SaveInvoices',
data: js,
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (data) {
calculateTotal();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
sendErrorEmail(window.location.href, 'SaveInvoices', XMLHttpRequest);;
}
});

Why my data is not updating?

I am trying to update ClientInfo table. But it is not updating and shows that Undefined. Those code below i have used in my controller for updating my database table data. Where is my problem i cannot find out? experts please help me..
[HttpPost]
public JsonResult Update(ClientInfo clnt, int id)
{
if (ModelState.IsValid)
{
ClientInfo c = db.Query<ClientInfo>("Select * from ClientInfo Where CId=#0", id).First<ClientInfo>();
c.CName = clnt.CName;
c.CCName = clnt.CCName;
c.Address = clnt.Address;
c.PhoneNo = clnt.PhoneNo;
c.Fax = clnt.Fax;
c.Email = clnt.Email;
c.Country = clnt.Country;
c.PostalCode = clnt.PostalCode;
c.Update();
return Json(c, JsonRequestBehavior.AllowGet);
}
else
return Json(new { msg = "Fail to Update Client Info." + id });
}
And Search Controller For searching Data
public JsonResult Search2(string id=null)
{
if (id != null)
{
var sresult = db.Query<ClientInfo>("Where CId=" + id).ToList<ClientInfo>();
return Json(sresult, JsonRequestBehavior.AllowGet);
}
else
return null;
}
And my ajax call from views For searching data by cid value..
#section scripts{
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Styles.Render("~/Content/themes/base/css")
<script type="text/javascript">
$(document).ready(function () {
$('#CId').blur(function () {
var v = $('#CId').val();
var url = "/Clients/Search2/" + v;
// alert("Test : " + url);
$("#CName").val("");
$("#CCName").val("");
$("#PhoneNo").val("");
$("#Fax").val("");
$("#Email").val("");
$("#Address").val("");
$("#PostalCode").val("");
$("#Country").val("");
$.getJSON(url, null, function (data, status) {
$.each(data, function (index, C) {
$("#CName").val(C.CName);
$("#CCName").val(C.CCName);
$("#PhoneNo").val(C.PhoneNo);
$("#Fax").val(C.Fax);
$("#Email").val(C.Email);
$("#Address").val(C.Address);
$("#PostalCode").val(C.PostalCode);
$("#Country").val(C.Country);
});
});
});
For database update i have used this function ...
$('#btnUpdate').click(function () {
var CId = $("#CId").val();
var CName = $("#CName").val();
var CCName = $("#CCName").val();
var PhoneNo = $("#PhoneNo").val();
var Fax = $("#Fax").val();
var Email = $("#Email").val();
var Address = $("#Address").val();
var PostalCode = $("#PostalCode").val();
var Country = $("#Country").val();
var client1 = {
"CId": CId,
"CName": CName,
"CCName": CCName,
"PhoneNo": PhoneNo,
"Fax": Fax,
"Email": Email,
"Address": Address,
"PostalCode": PostalCode,
"Country": Country
};
var lk = "/Clients/Update/" + CId;
//alert("Test : Update " + lk + "\n" + client1.Country);
client = JSON.stringify(client1);
$.ajax({
cashe: false,
async: false,
url: lk,
type: 'POST',
data: client,
dataType: "json",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert(data.msg);
}
});
});
});
</script>
}
If you mean Undefined in your alert message box, it's simple:
$.ajax({
cashe: false,
async: false,
url: lk,
type: 'POST',
data: client,
dataType: "json",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert(data.msg);
}
});
Your ajax code displays the content of data.msg. But when your model is valid, it retrieves the model from the database, updates it and returns the new model. There is no msg json property if it succeeds, hence data.msg is undefined.
If you want it to return a success message, you need to change
return Json(c, JsonRequestBehavior.AllowGet);
into
return Json(new { msg = "Update Successful.", record = c }, JsonRequestBehavior.AllowGet);
then you will have a message in data.msg and your newly updated record in data.record.
DBContext have a save method you must run this.
Did you run Save(); method ?

Categories