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.
Related
I've been trying to complete a requirement which has a textbox where I need to do a autoComplete functionality. I have a Model which has two properties, Name and Value. So, I am a list of CityNames and their Id's. So on entering the name, system should get the Id. I've been trying alot but din't found any solution. Could anyone help me please!!
Here is my Controller
[HttpPost]
public JsonResult FillViewData(string term)
{
List<City> list = new List<City>()
{
new City{ Name = "Vijay", Id = 1 },
new City{ Name = "Ratan", Id = 2 },
new City{ Name = "Payo", Id = 3 },
new City{ Name = "Hari", Id = 4 },
new City{ Name = "Krish", Id = 5 }
};
var CityName = (from N in list
where N.Name.StartsWith(term)
select new { N.Name });
return Json(CityName, JsonRequestBehavior.AllowGet);
}
View:
#Html.TextBox("searchName", null,new { name = "txtSearch"})
JS:
<script type="text/javascript">
$("#txtSearch").autocomplete({
source: function (request, response) {
$.ajax({
url: 'Home/FillViewData',
type: "POST",
dataType: JSON,
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
}
})
}
});
Change url format like this
url: '/Home/FillViewData',
I want to be able to display the ViewBag on view on button click event, this is my code:
[HttpPost]
public ActionResult SpecificWorkflowReport(Report2ListViewModel wf)
{
var getSpRecord = db.Mworkflow().ToList();
var getRecord = (from u in getSpRecord
select new Report2ListViewModel
{
WorkFlowType = u.WorkFlowType,
WorkflowInstanceId = u.WorkflowInst,
WorkFlowDescription = u.WorkFlowDesc,
}).ToList();
ViewBag.WorkflowType = wf.WorkFlowType;
ViewBag.WorkflowInstanceId = wf.WorkflowInst;
ViewBag.WorkFlowDescription = wf.WorkFlowDesc
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getRecord);
return Json(data);
}
i have tried this:
Worflow Type: #ViewBag.WorkflowType
Workflow Instance Id: #ViewBag.WorkflowInstanceId
Workflow Description: #ViewBag.WorkFlowDescription
My Javascript and json Call:
<script type="text/javascript">
$(function () {
var table = $("#reportTable").DataTable();
var url = $("#frmSpecificWorkflowReport").attr('action');
var str = $("#frmSpecificWorkflowReport").serialize();
$.ajax({
url: url,
type: "POST",
data: str,
cache: false,
dataType: "json",
success: function (_data) {
if (_data.f !== undefined) {
swal({
title: "Empty Result Set",
text: "No record found",
type: "info"
});
table.clear();
return false;
}
var arr = $.map(JSON.parse(_data), function (el) { return el
});
if (arr.length === 0) {
swal({
title: "Empty Result Set",
text: "No record found",
type: "info"
});
}
table.clear();
table.destroy();
$('#reportTable').dataTable({
data: arr,
columns: [
{ "data": "WorkFlowType" },
{ "data": "WorkflowInstanceId" },
{ "data": "WorkFlowDescription" },
],
dom: 'Bfrtip',
buttons: [
'copy', 'csv', 'excel',
{
extend: 'pdfHtml5',
orientation: 'landscape',
pageSize: 'LEGAL'
}
]
});
table = $("#reportTable").DataTable();
but the ViewBag values are always null on the view, any assistance will be appreciated. I just added Javascript and json call to the post, i want to be able to retrieve my stored data and display it anywhere on the view
#UwakPeter your code snippets is ok, but you are returning Json, may be you are calling this method via javascript, so the view is not updating, you need to reload the view, by the submit button.
If you are using javascript, you can pass your data list and model data as anonymous object, so that you don't need to use ViewBag. in client side by ajax success function you can grab them (WorkflowType, WorkflowInstanceId, WorkFlowDescription, Result)
[HttpPost]
public ActionResult SpecificWorkflowReport(Report2ListViewModel wf)
{
var getSpRecord = db.Mworkflow().ToList();
var getRecord = (from u in getSpRecord
select new Report2ListViewModel
{
WorkFlowType = u.WorkFlowType,
WorkflowInstanceId = u.WorkflowInst,
WorkFlowDescription = u.WorkFlowDesc,
}).ToList();
var data = Newtonsoft.Json.JsonConvert.SerializeObject(getRecord);
return Json(new{
WorkflowType = wf.WorkFlowType,
WorkflowInstanceId = wf.WorkflowInst,
WorkFlowDescription = wf.WorkFlowDesc,
Result= data
}, JsonRequestBehaviour.AllowGet);
}
JS
$.ajax({
url: url,
type: "POST",
data: str,
cache: false,
dataType: "json",
success: function (_data) {
var workflowType=_data.WorkflowType; //set it to HTML control
var workflowInstanceId =_data.WorkflowInstanceId;
var workFlowDescription = _data.WorkFlowDescription;
$('#reportTable').dataTable({
data: _data.Result
});
}
)};
Try this,
#{
Layout = null;
ProjectMVC.Models.Record record= (ProjectMVC.Models.Record)ViewBag.Recorddetails;
}
...
Worflow Type: #record.WorkflowType
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 });
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 ?
I have an MVC JsonResult Method that accepts one string parameter:
public JsonResult GetDestinations(string countryId)
{
List<Destination> destinations = new List<Destination>();
string destinationsXml = SharedMethods.GetDestinations();
XDocument xmlDoc = XDocument.Parse(destinationsXml);
var d = from country in xmlDoc.Descendants("Country")
from destinationsx in country.Elements("Destinations")
from destination in destinationsx.Elements("Destination")
where (string)country.Attribute("ID") == countryId
select new Destination
{
Name = destination.Attribute("Name").Value,
ID = destination.Attribute("ID").Value,
};
destinations = d.ToList();
return Json(new JsonResult { Data = destinations}, JsonRequestBehavior.AllowGet);
}
With a jquery method calling the method:
//Fetch Destinations
$("#Country").change(function () {
var countryId = $("#Country > option:selected").attr("value");
$("#Destination").html("");
$("#Resort").html("");
$("#Resort").append($("<option></option>").val(0).html("---Select---"));
$.ajax({
type: "POST",
traditional: true,
url: "/Destinations/GetDestinations",
data: "{countryId:'" + countryId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
BindDestinationSelect(msg)
}
});
});
However, the JsonResult seems to only receive a null parameter. Even though Firebug is showing that a parameter is being passed:
JSON
countryId
"11"
Source
{countryId:'11'}
Any ideas? Thanks
I think the problem is in how you are actually passing the data, you are doing so as a string:
data: "{countryId:'" + countryId + "'}",
When in reality, you should be using a structure on the client side;
data: { countryId: countryId },
jQuery should be able to handle passing the id correctly then. As you are doing it now, it is trying to send JSON to the server, which is not what MVC is expecting, it's expecting a POST with name/value pairs.
You might also want to consider the jQuery Form Plugin, as it makes serializing your Javascript structures into POST data very easy.
Ah, after much searching I've discovered the reason why it fails.
Nothing to do with malformed JSON etc, but rather the fact that the controller method doesnt know what to expect if you try to pass it JSON values:
http://www.c-sharpcorner.com/Blogs/BlogDetail.aspx?BlogId=863
So in my case, I've just elected to pass it a single string value.
$("#Country").change(function () {
var countryId = $("#Country > option:selected").attr("value");
$("#Destination").html("");
$("#Resort").html("");
$("#Resort").append($("<option></option>").val(0).html("---Select---"));
$.ajax({
type: "POST",
traditional: true,
url: "/Destinations/GetDestinations",
data: "countryId=" + countryId,
success: function (msg) {
BindDestinationSelect(msg.Data)
}
});
Here I suggest you to decorate your action with HttpPost attribute
Like :-
[HttpPost]
public JsonResult GetDestinations(string countryId)
{
List<Destination> destinations = new List<Destination>();
string destinationsXml = SharedMethods.GetDestinations();
XDocument xmlDoc = XDocument.Parse(destinationsXml);
var d = from country in xmlDoc.Descendants("Country")
from destinationsx in country.Elements("Destinations")
from destination in destinationsx.Elements("Destination")
where (string)country.Attribute("ID") == countryId
select new Destination
{
Name = destination.Attribute("Name").Value,
ID = destination.Attribute("ID").Value,
};
destinations = d.ToList();
return Json(new JsonResult { Data = destinations}, JsonRequestBehavior.AllowGet);
}
public JsonResult BindAllData(string Userid)
{
List<VoteList> list = new List<VoteList>();
var indexlist = db.TB_WebSites.ToList();
int i = 0;
var countlist = db.Tb_Votes.ToList();
var VCountList = db.Tb_Votes.ToList();
foreach (TB_WebSites vt in indexlist)
{
bool voted = false;
}
return Json(new { List = _list });
}
function DataBind() {
$("#LoadingDatas").show();
var userid = $("#FBUserId").text();
//alert('Data : ' + userid);
var InnerHtml = "";
$.ajax(
{
url: '/Gitex/BindAllData/',
type: 'POST',
data: { "Userid": userid },
dataType: 'json',
async: true,
success: function (data) {
//alert('Done');
//alert(data.List.length);
for (var i = 0; i < data.List.length; i++) {
});
}
Try this, it worked for me
jQuery function
success :function(Destinations)