I am trying to follow this example
and I have the following in JSP page
(getData.jsp)
Department t = new Department ();
String query = request.getParameter("q");
List<String> tenders = t.getDepartments(query);
Iterator<String> iterator = tenders.iterator();
while(iterator.hasNext()) {
String deptName= (String)iterator.next();
String depto = (String)iterator.next();
out.println(deptName);
}
How can I use the above to use in Jquery autcomplete? When I tried there was no output coming.
My Jquery autoComplete code
<script>
$(function() {
$( "#dept" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "getData.jsp",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map( data.<??>, function( item ) {
return {
label: item.name + (item.<??> ? ", " + item.<??> : "") + ", " + item.<??>,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
alert(ui.item.label);
}
});
});
</script>
Is your response in JSON format?
Here's what I do when I use Jquery UI Autocomplete:
Create a class whose parameters are the ones you will use when you say item.name
public string Pam1{ get; set; }
public string Pam2{ get; set; }
public string Pam3{ get; set; }
public SomeResponse(string SomePam)
{
// Pam1 = ???
// Pam2 = ???
// Pam3 = ???
}
In your handler:
context.Response.ContentType = "application/json";
string query = (string)context.Request.QueryString["query"];
var json = new JavaScriptSerializer();
context.Response.Write(
json.Serialize(new SomeResponse(query))
);
context.Response.Flush();
context.Response.End();
EDIT
The javascript (Here is an example where the user can choose more than one option, separated by coma. If you don't want that, remove it.) txt_autocomplete is the class of the TextBox.
$(function () {
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$(".txt_autocomplete")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
source: function (request, response) {
$.getJSON("handlers/autocomplete.ashx?query=" + extractLast(request.term), {
term: extractLast(request.term)
}, response);
},
search: function () {
var term = extractLast(this.value);
if (term.length < 2) {
return false;
}
},
focus: function () {
return false;
},
select: function (event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.Pam1);
terms.push("");
this.value = terms.join(", ");
console.log("Pam1 is :" + ui.item.Pam1 + " Pam2 is: " + ui.item.Pam2 + " Pam 3 is : " + ui.item.Pam3);
return false;
}
});
});
Related
Good day, i'm new to webix and codeigniter, i wanna ask if after getting the json from controller the format is like {End_date: "2019-07-31", value: "2019-07-31"} in console log, how to display on webix text?
function GetEndDate() {
return $.ajax('<?php echo base_url(); ?
>index.php/date/dateController/GetEndDate/' + Id);
}
webix.ready(function(){
$.when(GetEndDate()).done(function(EndDates){
EndDate = EndDates[0];
rendersformSection();
});
});
function rendersformSection(){
{view:'text', id:'Final_date', name:'Final_date', labelAlign:
'right',label:'Final Date', labelWidth:200,
suggest: {
filter: function (item, value) {
if (item.value.toString().toLowerCase().indexOf(value.toLowerCase()) >= 0)
return true;
return false;
},
body: {
data: EndDate,
datatype: "json",
template: function(obj){
return obj.End_date;
}
}
},
on: {
onBeforeShow: function () {
var texts = [];
EndDate.forEach(function (obj) {
texts.push(obj.value);
});
}
}
webix.ui(rendersformSection);
}
I expect when the page load. the final date will show the date get from the function GetEndDate().
in controller json method getting columnnames (Account,EmailTo,Subject,MessageContent) like this in ReportColumnsList ..but i need to pass these values in view page and display in listbox..
data is getting as [Object Object] and also displaying in listbox like this..
please give me solution regarding this..
Thanks & Regards
in Controller part :-
[AllowAnonymous]
public ActionResult GetColumnsByFavouriteReport(ReportsModel Model,string Columns)
{
List<Report> ReportColumnsList = MCPAdminControllerPageObject.GetColumnsByReportName(Columns);
return Json(ReportColumnsList, JsonRequestBehavior.AllowGet);
}
In view Part:-
$(document).ready(function () {
$('#FavouriteReports').change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("GetColumnsByFavouriteReport", "MCPAdmin")',
data: { Columns: $('#FavouriteReports').val() },
datatype: "json",
traditional: true,
success: function (data) {
$('#SelectedFields').empty();
$.each(data, function (key, val) {
$('#SelectedFields').append('<option id="' + key + '">' + val + '</option>');
})
}
});
});
#Html.ListBoxFor(m => m.SelectedFields, new SelectList(new[] { "" }), new { #class = "form-control editable" })
Let me assume Your model class Report
public class Report {
public int ReportId { get; set; }
public Name ReportName { get; set; }
}
Inside your ajax method
if(data!=null) {
$('#SelectedFields').empty();
var dd = null ;
$.each(data, function (key, val) {
dd += "<option " + " value=" + val.ReportId + ">" + val.ReportName + "</option>";
});
//append to given id
$('#SelectedFields').append(dd);
}
I hope this will help your, bind your dropdown list
im working on ASP.NET MVC 4 project. well i already insert data into a SQL Server database using jQuery using a post method in .
Now im trying to insert data into 2 tables using the same view, my problem is that i can't passing multiple POST parameters to Web API Controller Method. here is my js function and my controller code, ill apreciate your help
var add_ClientPreste = function () {
var dataContrat = {
REFCONTRAT : 'mc1' ,
DATECREATION : '2016-05-23',
DATEFINCONTRAT : '2016-05-23'
};
var dataClient = {
C_IDCLIENTGROUPE : 11 ,
C_IDLOCALITE:332,
DATECREATION : '2016-05-23',
DATEMODIFICATION : '2016-05-23',
CODECLIENTPAYEUR : '999999999' ,
NOMCLIENTPAYEUR : 'morad'
};
$.ajax({
type: 'POST',
url: 'add_ClientPayeurContrat',
dataType: 'json',
data:{dataClient},
success: function (data) {
if(data==0) {
alert("enregistrement avec success : " );
}
else {
alert("error : "+ data );
}
},
error : function(data1) {
alert("aaaaaaaaaaaaaa " +data1);
}
});
}
$('#btntest').on('click', function () {
add_ClientPreste();
});
$('#btntest').on('click', function () {
add_ClientPreste();
});
Controller code
[HttpPost]
public ActionResult add_ClientPayeurContrat(SIG_CLIENTPAYEUR dataClient, SIG_CONTRAT dataContrat)
{
string msg = "";
try
{
ModSigma1.SIG_CLIENTPAYEUR.Add(dataClient);
ModSigma1.SIG_CONTRAT.Add(dataContrat);
ModSigma1.SaveChanges();
msg = "0";
}
catch (Exception ex)
{
msg = ex.Message;
}
return new JsonResult { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
var add_ClientPreste = function () {
var dataContrat = {
REFCONTRAT : 'mc1' ,
DATECREATION : '2016-05-23',
DATEFINCONTRAT : '2016-05-23'
};
var dataClient = {
C_IDCLIENTGROUPE : 11 ,
C_IDLOCALITE:332,
DATECREATION : '2016-05-23',
DATEMODIFICATION : '2016-05-23',
CODECLIENTPAYEUR : '999999999' ,
NOMCLIENTPAYEUR : 'morad'
};
$.ajax({
type: 'POST',
url: 'add_ClientPayeurContrat',
dataType: 'json',
data:{dataClient: dataClient},
success: function (data) {
if(data==0){
alert("enregistrement avec success : " );
}
else {
alert("error : "+ data );
}
},
error : function(data1){
alert("aaaaaaaaaaaaaa " +data1);
}
});
}
$('#btntest').on('click', function () {
add_ClientPreste();
});
$('#btntest').on('click', function () {
add_ClientPreste();
});
//controller code
[HttpPost]
public ActionResult add_ClientPayeurContrat(SIG_CLIENTPAYEUR dataClient, SIG_CONTRAT dataContrat)
{
string msg = "";
try
{
ModSigma1.SIG_CLIENTPAYEUR.Add(dataClient);
ModSigma1.SIG_CONTRAT.Add(dataContrat);
ModSigma1.SaveChanges();
msg = "0";
}
catch (Exception ex)
{
msg = ex.Message;
}
return new JsonResult { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
you did not add dataClient: dataClient in ajax.
so please add this.
Hope this will help you.
How to return multiple variables on JsonResult method
for example i want to return this two variables:
string result = "Successed";
string ID = "32"
I know how to return only one string:
return Json("Inserted");
public ActionResult YourAction()
{
var result=new { Result="Successed", ID="32"};
return Json(result, JsonRequestBehavior.AllowGet);
}
EDIT : As per the comment "How to get this data in client"
You can use getJSON from view to get this data like this
$(function(){
$.getJSON('YourController/YourAction', function(data) {
alert(data.Result);
alert(data.ID);
});
});
Make sure you have jQuery loaded in your view for this code to work.
Return an anonymous object.
return Json( new { Result = result, Id = ID } );
I normally do something like this:
public enum NoticeTypes
{
Default,
UpdateComplete,
ResponsePending,
Notice,
Error,
Redirect,
WaitAndRetryAttempt
}
public class AjaxJsonResponse
{
public UserNotice Notice { get; set; }
public object Data { get; set; }
private AjaxJsonResponse() { }
public static JsonResult Create(UserNotice Notice,object Data)
{
return new JsonResult()
{
Data = new
{
Notice = Notice,
Data = Data
}
};
}
}
So that I can write my javascript to always expect ajax calls to return data in a certain format.
return AjaxResponse.Create(NoticeTypes.UpdateComplete, new
{
Result = result,
Id = ID
});
Now you can do things like an Ajax Complete global handler that can intercept things like Redirect or WaitAndRetry before the normal handler gets it, and to have a standard way of communicating additional information about the returned data that is the same across your application.
On your controller use something like this:
var result = new { data= stuff, data2 = otherstuff };
return Json(result, JsonRequestBehavior.AllowGet);
If you are using .ajax() on your JavaScript you can use your data acessing like this:
$.ajax(
{
url: '/Controller/Method/',
type: 'POST',
data: 'data=' + data,
success: function (result) {
$('#id').html("");
$(result.data).appendTo('#id');
$('#id2').html("");
$(result.data2).appendTo('#id2');
$('#id').show();
$('#id2').show();
}
});
1. Return as collection inside anonymous type
This is the java script/ajax call and the complete html.
< script type = "text/javascript" >
$(document).ready(function() {
$("#ddlProduct").hide();
$("#ddlRegion").change(function() {
$("#ddlProduct").show();
$("#ddlProduct").empty();
$.ajax({
type: "Post",
url: "#Url.Action("
GetProducts ")",
dataType: "Json",
data: {
id: $("#ddlRegion").val()
},
success: function(jsonData) {
console.log($(jsonData).length);
if ($(jsonData.ProductList).length == 0) {
$("#divProduct").hide();
} else {
$("#divProduct").show();
}
$.each(jsonData.ProductList, function(i, Product) {
$("#ddlProduct").append('<option value=" ' + Product.Value + ' ">' + Product.Text + '</option>');
});
if ($(jsonData.FlavourList).length == 0) {
$("#divFlavour").hide();
} else {
$("#divFlavour").show();
$.each(jsonData.FlavourList, function(i, flavour) {
$("#ddlFlavour").append('<option value=" ' + flavour.Value + ' ">' + flavour.Text + '</option>');
});
}
},
error: function(ex) {
alert("Failed to return Products <br/>");
}
});
return false;
})
}); //Document Ready Ends
< /script>
#{ ViewBag.Title = "Products Drop Down Demo"; }
<h2>Products Drop Down Demo</h2>
#using (Html.BeginForm()) {
<div>#Html.Label("Select Region:")</div>
<div class="editor-field">
#if (ViewData.ContainsKey("Region")) { #Html.DropDownList("ddlRegion", ViewData["Region"] as List
<SelectListItem>) }
</div>
<div id="divProduct" hidden="hidden">
<br />
<div>
Select a Product:
</div>
<div>
#Html.DropDownList("ddlProduct", new SelectList(string.Empty, "Value", "Text"), "Please select a Product", new { style = "width:250px", #class = "dropdown1" })
</div>
</div>
<div id="divFlavour" hidden="hidden">
<div>
<br />Select a Flavour:
</div>
<div>
#Html.DropDownList("ddlFlavour", new SelectList(string.Empty, "Value", "Text"), "Please select a Flavour", new { style = "width:250px", #class = "dropdown1" })
</div>
</div>
}
This is the controller action that returns the data
I tested and it is working.
public ActionResult LoadRegion()
{
List<SelectListItem> Regions = new List<SelectListItem>();
Regions.Add(new SelectListItem { Text = "Select A Region", Value = "0" });
Regions.Add(new SelectListItem { Text = "Asea", Value = "1" });
Regions.Add(new SelectListItem { Text = "Australia", Value = "4" });
Regions.Add(new SelectListItem { Text = "America", Value = "5" });
Regions.Add(new SelectListItem { Text = "Europe", Value = "6" });
ViewData["Region"] = Regions;
return View();
}
public JsonResult GetProducts(string id)
{
List products = new List();
List flavours = new List();
products.Add(new SelectListItem { Text = "Select Product", Value = "0" });
products.Add(new SelectListItem { Text = "Cheese", Value = "1" });
products.Add(new SelectListItem { Text = "Sause", Value = "2" });
products.Add(new SelectListItem { Text = "Veberage", Value = "3" });
products.Add(new SelectListItem { Text = "Snacks", Value = "4" });
flavours.Add(new SelectListItem { Text = "Select Flavour", Value = "0", Selected = true });
flavours.Add(new SelectListItem { Text = "Sweet", Value = "1" });
flavours.Add(new SelectListItem { Text = "Sour", Value = "2" });
flavours.Add(new SelectListItem { Text = "Spicy", Value = "3" });
var myResult = new
{
ProductList = products,
FlavourList = flavours
};
return Json(myResult, JsonRequestBehavior.AllowGet);
}
Let me know if you have any issue running this code.
Thanks
Premjeet
You should return an object with multiple properties:
return Json(new {
result,
ID
});
The JSON serializer will convert C# anonymous types into JSON object literals.
In Action method :
Using new keywork
var genericResult = new { homeworkData = homework, attachmentData = homeworkAttachment };
var result = this.Json(genericResult, JsonRequestBehavior.AllowGet);
return result;
In jquery side :
function getHomewrokDetailResponse(dataSent, result) {
if (result && result.homeworkData) {
homeworkId = result.homeworkData.DASH_EMPLOYEE_HOMEWORK_ID;
....
}
I have a <select> which is loaded by a JSon. But I want to use "#html.dropdownlist helper" instead. My Json is:
function LoadSites() {
$("SelectSite").html("");
$.getJSON("/Pedido/GetSite", null, function (data) {
$("#SelectSite").append("<option value=0>Selecione...</option>");
$.each(data.Result, function (index, site) {
$("#SelectSite").append("<option value='" + site.Id + "'>" + site.Nome + "</option>");
});
});
this Json populate this...
<select id="SelectSite"></select>
My Controller:
[HttpGet]
public JsonResult GetSite()
{
Repository<Site> siteRepo = new Repository<Site>( unitOfWork.Session );
return this.Json( new { Result = siteRepo.All() }, JsonRequestBehavior.AllowGet );
}
I want my code more reusable and self-documenting.
How can I send the object "site" from JSon to "cshtml" using dropdownlist to do something like #html.dropdownlist(site.id, site.Nome)???
Is there a way?
Tks guys.
In your view:
#Html.DropDownListFor(x => x.SiteId, new SelectList(Enumerable.Empty<SelectListItem>()))
where SiteId is a property of your view model which will receive the selected site id when the form is submitted.
and then you could populate this dropdown using AJAX:
$(function() {
$.getJSON('#Url.Action("GetSite", "Pedido")', function(result) {
var ddl = $('#SiteId');
ddl.empty();
$(result).each(function() {
ddl.append(
$('<option/>', {
value: this.Id
}).html(this.Nome)
);
});
});
});
and the controller action that would return the JSON data:
public ActionResult GetSite()
{
var sites = new[]
{
new { Id = "1", Nome = "site 1" },
new { Id = "2", Nome = "site 3" },
new { Id = "3", Nome = "site 3" },
};
return Json(sites, JsonRequestBehavior.AllowGet);
}