Consistently get data from action in controller with in MVC $.ajax()? - c#

I have this code in my controller:
int number = 0;
public JsonResult JsonData()
{
for (int i = 0; i < 21; i++)
{
number += i;
return Json(number, JsonRequestBehavior.AllowGet);
}
return Json(number, JsonRequestBehavior.AllowGet);
}
And loop with jQuery Ajax script in the view:
<script type="text/javascript">
var tag = true;
$(document).ready(function () {
while (tag) {
$.ajax({
url: "#Url.Action("JsonData", "Home")",
dataType: 'json',
success: function (data) {
console.log(data);
$('#counter').html('');
$('#counter').html(data);
if (data == 20) {
tag = false;
}
}
});
}
});
</script>
<div id="counter"></div>
My goal is to make jQuery Ajax to constantly get "number" from action "JasonData" and print that number to "DIV tag" But my current code is not working for some reason, - the result is that browser window will not stop loading if i'm using "while()" loop, if I'm not using "while()" loop it only prints the first value of "number" variable.

Use a setInterval/setTimeout instead of while loop, because continuously running script will block the UI and you can utilize the callback mechanism instead.
$(document).ready(function () {
var interval = window.setInterval(function(){
$.ajax({
url: "#Url.Action("JsonData", "Home")",
dataType: 'json',
success: function (data) {
$('#counter').html(data);
if (data == 20) { //<-- make sure data has value 20 and is not an object or anything
window.clearInterval(interval);
}
}
});
}, 1000); //<-- Give interval in milliseconds here
});
Demo
Or with timeout:
$(document).ready(function () {
makeAjaxCall();
});
function makeAjaxCall(){
$.ajax({
url: "#Url.Action("JsonData", "Home")",
dataType: 'json',
success: function (data) {
$('#counter').html(data);
if (+data < 20) {
window.setTimeout(makeAjaxCall, 1000); //Duration in ms
}
}
});
}
Demo

Related

Creating Hyperlinks for Append(Response) Output

Can someone please help me out on how to create a hyperlink for the output from append(response).
<script type="text/javascript">
$(document).ready(function () {
$("#Sid").change(function () {
if (document.getElementById("Sid").selectedIndex == 0) {
$("#Did").empty();
}
else {
var SitId = $(this).val();
debugger
$.ajax({
type: "post",
url: "/Dropdown/GetDeviceList?Sid=" + SitId,
contentType: "html",
success: function (response) {
debugger
$("#Did").empty();
$("#Did").append(response);
If the response is a url string :
$("#Did").append(`link text`)

Auto-complete select multiple tags in asp.net

Anyone can tell me how can i use tokenizing in auto-complete for multiple selection, I am make you sure that, i want only with asp.net web from web service
My Code:
$(function () {
// Web servcice javascript code for City
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/WebServices/WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{ 'username': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d.length > 0) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
};
}))
} else {
response([{ label: 'No results found.', val: -1 }]);
}
}
});
},
select: function (e, u) {
if (u.item.val == -1) {
return false;
}
}
});
});
I want to use a web service to fetch data from database and show on front-end for multiple selection
Web Service:
DataTable dt = userRegistrationHelper.GetSkillsList(username);
DataRow[] rows = null;
rows = dt.Select(string.Format("SkillName = {0}", username));
string[] result = new string[rows.Length];
for (int i = 0; i <= rows.Length - 1; i++)
{
result[i] = rows[i]["SkillName"].ToString();
}
return result;
Autocomplete with multiple words or values with comma separated
$(function () {
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("~/WebServices/WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("[id*=ctl00_ContentMain_TextBoxSkills]").bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
});

Pass variable from jquery to code behind

<asp:Button ID="Button1" runat="server" Text="Submit" />
<script>
$(document).ready(function () {
$("#Button1").click(function () {
var list = [];
var a= $("#TextBox1").val();
var b= $("#TextBox2").val();
var count = a* b;
list.push('test');
for (var i = 1; i <= count; i++) {
var item = $("#DropDownList_" + i + "_").find(":selected").text();
list.splice(i, 0, item);
console.log(list.join());
alert(list[i]);
}
});
});
</script>
Hello guys first time at the stack! I have this jquery code that get all choices of dropdown list and store it in array.
I want pass this array to c# so I can store the values in DB, please help.
You can simply do this using jQuery ajax:-
var dataToSend = { "Data": list};
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/SaveData",
data: JSON.stringify(dataToSend),
success: function (msg) {
//success data if any
},
error: function (msg) { //handle error here }
});
Add this method in your page behind (Default.aspx.cs):-
[WebMethod]
public static void SaveData(string[] Data)
{
//Save data to DB
}

How to load new data after click next or back Fullcalendar

I am using Fullcalendar plugin which is integrated with my ASP.NET MVC project. My main task consists of creating a schedule of reservations. I have written the code which is responsible for displaying events("Buttons") for specific date, and it works fine!. Code below:
var calendar = $("#calendar").fullCalendar({
weekends: false
, lang: 'pl',
header: {
left:'',
center: 'title',
right: 'today prev,next'
}, height: 630, week: true, columnFormat: 'dd M/D', minTime: '8:00', maxTime: '20:00', selectable: true,
allDaySlot: false, eventColor: '#F6A828',
events: function (start, end, timezone, callback) {
$.ajax({
url: '/Dentist/GetEvents/',
type: 'POST',
contentType: "application/json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
callback(json)
//
}
});
},
})
$('#calendar').fullCalendar('changeView', 'agendaWeek');
and method GetEvents in C#
public JsonResult GetEvents()
{
if (Session["DoctorID"] == null)
{
return Json(new { redirectUrl = Url.Action("Terminarz", "Recepcjonista"), isRedirect = true });
}
var listEvent = new List<CallendarEvent>();
List<CallendarEvent> list = TermRepository.GetAllEventsByDoctorId((int)Session["DoctorID"]);
int licznik = 1;
foreach (var item in list)
{
int count = Size(item.id, item.From, item.To);
for (int i = 0; i < count; i++)
{
listEvent.Add(new CallendarEvent()
{
id = licznik,
day = item.day,
Title = item.Title,
From = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30),
To = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30).AddMinutes(30)
});
licznik++;
}
}
var listEvent2 = from l in listEvent
select new
{
id = l.id,
//day = l.day,
//Title = l.Title,
start = l.From,
end = l.To,
color = "#88CD23"
};
return Json(listEvent2, JsonRequestBehavior.AllowGet);
}
and now I would like to handle next and back buttons and change start date, end +7 day. I wrote something like this, but doesn't work
C#
public JsonResult GetEventsAdd(int move)
{
//all the same method as in GetEvents, but added days
listEvent.Add(new CallendarEvent()
{
id = licznik,
day = item.day,
Title = item.Title,
From = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30).AddDays(move),
To = GetDay(item.day).AddHours(item.From.TimeOfDay.Hours).AddMinutes(item.From.TimeOfDay.Minutes).AddMinutes(i * 30).AddMinutes(30).AddDays(move)
});
licznik++;
}
}
//all the same method as in GetEvents
return Json(listEvent2, JsonRequestBehavior.AllowGet);
}
and script was changed
events: function (start, end, timezone, callback) {
var data = { "move": 7 }
$.ajax({
url: '/Dentist/GetEvents/',
type: 'POST',
//data: JSON.stringify(calendar),
//datatype: "json",
contentType: "application/json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
callback(json)
//
}
});
$(".fc-next-button").one("click", function () {
$.ajax({
url: '/Dentist/GetEventsAdd/',
type: 'POST',
data: JSON.stringify(data),
datatype: "json",
contentType: "application/json",
success: function (json) {
if (json.isRedirect) {
window.location.href = json.redirectUrl;
}
callback(json)
//$('#calendar').fullCalendar('refetchEvents');
}
});
});
how can I get such a solution?
The AJAX call that fullcalendar makes passes the start and end date range for the current view. It will then call that again, only if it doesn't have the date stored.
so in your /Dentist/GetEvents/
grab the "GET" variables: "START" and "END".
return the events that are in that range.
then simply use the native 'next', 'prev' buttons from fullcalendar and let it do its thing.

asp.net MVC pass server value to hidden field

From my OnePageCheckout.cshtml View i call ajax controller
#Html.Hidden("StepContent", (string)ViewBag.newAddress) #* never work *#
$.ajax({
cache: false,
url: this.saveUrl,
data: $(this.form).serialize(),
type: 'post',
success: this.nextStep, // still stay in the same page
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
public ActionResult OpcSaveBilling(FormCollection form) {
ViewBag.newAddress="abc";
return Json(new {
update_section = new UpdateSectionJsonModel() {
name = "confirm-order",
html = this.RenderPartialViewToString("OpcConfirmOrder", confirmOrderModel)
},
goto_section = "confirm_order"
});
}
How can I update the status of the hidden input with a value from the controller?
UPDATE 2:
var Billing = {
form: false,
saveUrl: false,
init: function (form, saveUrl) {
this.form = form;
this.saveUrl = saveUrl;
},
save: function () {
if (Checkout.loadWaiting != false) return;
Checkout.setLoadWaiting('billing');
$.ajax({
cache: false,
url: this.saveUrl,
data: $(this.form).serialize(),
type: 'post',
success: function (data) {
this.nextStep; << nextStep won't be called !! but it works for success: this.nextStep
},
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
},
resetLoadWaiting: function () {
Checkout.setLoadWaiting(false);
},
nextStep: function (response) {
alert('aa');
if (response.error) {
if ((typeof response.message) == 'string') {
alert(response.message);
} else {
alert(response.message.join("\n"));
}
return false;
}
$('#StepContent').val($("#billing-address-select").find('option:selected').text());
Checkout.setStepResponse(response);
}
};
Change status in JS after ajax call,
$.ajax({
cache: false,
url: this.saveUrl,
data: $(this.form).serialize(),
type: 'post',
success: function (data) {
$("#StepContent").val(data.status);
this.nextStep;
},
complete: this.resetLoadWaiting,
error: Checkout.ajaxFailure
});
and controller pass status in JSON
public ActionResult OpcSaveBilling(FormCollection form) {
ViewBag.newAddress="abc";
return Json(new {
update_section = new UpdateSectionJsonModel() {
name = "confirm-order",
html = this.RenderPartialViewToString("OpcConfirmOrder", confirmOrderModel),
},
status = "abc",
goto_section = "confirm_order"
});
}

Categories

Resources