I want to get new value from controller and set it to view when form submit.
Controller:
public JsonResult GetVoucherNo()
{
var voucherno = 1001;
var lastvoucherno = db.PaymentsAndReceipts.Where(x => x.StakeHolder.StakeHolderType.Name == "Supplier").OrderBy(x => x.VoucherNo).ToList().LastOrDefault();
if (lastvoucherno != null)
{
voucherno = lastvoucherno.VoucherNo.GetValueOrDefault() + 1;
}
return new JsonResult { Data = voucherno, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
My Jquery function:
I just want to do when this function calls, I can get the value from controller action.
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'Payments/GetVoucherNo',
dataType: "json"
}).done(function () {
//don't know what to do here.
});
}
The data should be available in the done function argument like this:
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'Payments/GetVoucherNo',
dataType: "json"
}).done(function (result) {
//don't know what to do here.
console.log(result);
//you should see the exact JSON you return from the controller
});
}
I done it with success.
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: '/Payments/GetVoucherNo',
dataType: "json",
success: function (result) {
console.log(result);
return $('#VoucherNo').val(result); //to set value in textbox.
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr, status, error);
}
});
}
Related
I've found a small problem in sending just plain text(string) via ajax compared to sending an json object.
I have currently this setup working
(cs)html
<label for="search">
<i class="fa fa-search" onclick="sendtoC()"></i>
<input type="search" id="search" placeholder="Sök här..." autofocus; />
<input type="button" id="SÖK" value="SÖK" onclick="sendtoC()" />
Script
<script>
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}
and current controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return Json(new { success = true, message = input }, JsonRequestBehavior.AllowGet);
}
I would like to just send a straight string to the controller and i tried this Script
function sendtoC() {
$.ajax({
url: "/Home/SearchResults",
dataType: "text",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: invalue ,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}});}
with this Controller
public ActionResult SearchResults(string input)
{
Data.gsPersonLista = db.GetPerson(input);
return View(input);
}
however this didn't work, the input string was shown to get value of null and ajax gave error. I currently have no idea of how to fix this nor what gives the error. If someone could Point me in the right direction I would appreciate it
You can simply use the $.get function here and secondly you should use the Ùrl.Action helper for getting the url against the controller action method, as the magic strings would cause issues in deployments where the application might be deployed in sub-directories and in those case the url becomes wrong :
$.get('#Url.Action("SearchResults","Home")?input='+invalue , function (data) {
if (data.success) {
alert(data.message);
}
});
You can easily pass it as a request parameter, since you've also set the type to "GET".
url: "/Home/SearchResults?input="+invalue
You also have to remove the data attribute. Let me know if it helps.
UPDATED ANSWER
datatype is what you are expecting to return from the server. Content type is what you are sending. so to return a view change datatype to htmL.
dataType: 'html',
the problem is that when you call the function sendtoC you are not receiving any parameters in the function. Change the function to accept a parameter.
var invalue;
var input = document.getElementById("search");
input.addEventListener("keyup", function go (event) {
if (event.keyCode === 13) {
invalue = document.getElementById("search").value;
sendtoC(invalue);
}
});
function sendtoC(invalue ) {
$.ajax({
url: "/Home/SearchResults",
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8', //define a contentType of your request
cache: false,
data: { input: invalue },
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
}
I have a List which look like the following
I want to send this list into my controller,
I am using ajax call to send data from client side to server side
here is my ajax call
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
and my method in controller
public bool updateHoliday(List<Holidaysclass> data)
{
for (var i = 0; i < data.Count(); i++)
{
insertHolidays(data.ElementAt(i).Date, data.ElementAt(i).Day, data.ElementAt(i).HolidayName, data.ElementAt(i).isActive, data.ElementAt(i).currentYear, data.ElementAt(i).isHolidayWeekend, data.ElementAt(i).OfficialID);
}
return true;
}
here my List<Holidaysclass> data is showing null
what can I do here?
To send data from browser to controller you need to use POST type and then pass data inside ajax call. you can directly map your entites in action method.
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
and in controller put HttpPost Data Annotation
[HttpPost]
public bool updateHoliday(List<Holidaysclass> data)
{
for (var i = 0; i < data.Count(); i++)
{
insertHolidays(data.ElementAt(i).Date, data.ElementAt(i).Day, data.ElementAt(i).HolidayName, data.ElementAt(i).isActive, data.ElementAt(i).currentYear, data.ElementAt(i).isHolidayWeekend, data.ElementAt(i).OfficialID);
}
return true;
}
Using ajax get method we cant send data from client to server is not best way. try using POST method send data from client to server.
Reference : https://api.jquery.com/jquery.post/
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
......
});
You can do it like this :
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/PassThings',
data: things,
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
Please follow this link for more information :
link
You can not post data in get request. Instead you need to use POST type request.
Here is your updated request.
$.ajax({
url: '/Main/updateTripundHoliday',
data: d.weekendLeave,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
Also your action should have [HttpPost] annotation.
try this:
$.ajax({
url: '/Main/updateHoliday',
data: {list: d.weekendLeave},
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
}
});
[HttpPost]
public bool updateHoliday(List<Holidaysclass> list)
I am writing CRUD application using ASP.NET MVC, KnockoutJS and database. When I write separate viewmodel for Create, Read, Update and Delete. and calling each view model in separate view (Create, Read, Update and Delete) then It's working fine. But when I include all view model in one single view model, then calling that view model in every View. Then I am neither able to create nor able to edit.
Please help me with this. I tried so many ways but could not get a proper solution.
I have written this function using Knockout:
$(function() {
ko.applyBindings(modelView);
});
Var parsedSelectedCourse = $.parseJSON(selectedCourse);
var modelView = {
Read: {
Courses: ko.observableArray([]),
viewCourses: function() {
var thisObj = this;
try {
$.ajax({
url: '/Home/ListCourses',
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function(data) {
thisObj.Courses(data); //Here we are assigning values to KO Observable array
},
error: function(err) {
alert(err.status + " : " + err.statusText);
}
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
},
Create: {
CourseName: ko.observable(),
CourseDescription: ko.observable(),
createCourse: function() {
try {
$.ajax({
url: '/Home/Create',
type: 'post',
dataType: 'json',
data: ko.toJSON(this), //Here the data wil be converted to JSON
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
},
Update: {
CourseID: ko.observable(parsedSelectedCourse.CourseID),
CourseName: ko.observable(parsedSelectedCourse.CourseName),
CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),
updateCourse: function() {
try {
$.ajax({
url: '/Home/Update',
type: 'POST',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
},
Delete: {
CourseID: ko.observable(parsedSelectedCourse.CourseID),
CourseName: ko.observable(parsedSelectedCourse.CourseName),
CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),
deleteCourse: function() {
try {
$.ajax({
url: '/Home/Delete',
type: 'POST',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
}
};
function successCallback(data) {
window.location.href = '/Home/Read/';
}
function errorCallback(err) {
window.location.href = '/Home/Read/';
}
why JSON doesn't work with html text (var text_html = '<p></p><t></t>'; ) but this will be work correct (var text_html = 'example';)
doesn't work
var text_html = JSON.parse('<p></p><t></t>');
Problem:
function Save() {
var text_html = '<p></p><t></t>';
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
My_Text: text_html
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
public JsonResult DodajTematSave(string My_Text)
{
return Json(new { Success = true});
}
also this doesn`t work
var dom_string = '<div>xxx<div>yyy</div></div>';
var text_html = dom_string.innerText();
also this doesn`t work
<script type="text/javascript">
function Save() {
var Temat_controll = $('#Temat').val();
var Streszczenie_controll = $.parseJSON('<p></p><t></t>');
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
dataType: "json"
});
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
try this:
var Streszczenie_controll = $.parseJSON('<p></p><t></t>');
and use ajaxSetup to instruct JQuery how to handle the data type
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Because those are escaping characters in JSON. You will have to parse html in a way to make it JSON friendly if you wanted it passed through JSON.
For this people who have problem with this I can show another way to fix this problem but very ugly click here
function pageLoad() {
$(".VoteUp").live("click", function () {
var Id = $(this).attr("index");
d = JSON.stringify({ "Id": Id })
$.ajax({
type: 'POST',
url: '../API/Services.asmx/LikeId',
data: d,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: testFunc,
error: errFunc
});
$(".VoteUp").each(function () {
$(this).attr("disabled", "disabled");
});
});
function testFunc(result, userContext, methodName) {
if (result.d[0] == "true") {
TheVoteUpControl.val("added");
}
else {
TheVoteUpControl.val("deleted");
}
$(".VoteUp").each(function () {
$(this).removeAttr("disabled");
});
}
function errFunc() {
alert('error');
}
How can I change the value of that same .VoteUp control on success? I can't seem to figure out how to target that same control who initiated the event. $(".VoteUp")
Suggestions?
the only way i can think of is cache the element in the global variable and catch it in the success callback. also i have moved the enabling and disabling of the $(".VoteUp") in the complete and beforeSend callbacks respectively
$(".VoteUp").live("click", function (e) {
e.preventDefault();
$this=$(this); <-- cache this in the global variable
var Id = $(this).attr("index");
d = JSON.stringify({ "Id": Id })
$.ajax({
beforeSend:function(){
$(".VoteUp").attr("disabled", "disabled");
},
type: 'POST',
url: '../API/Services.asmx/LikeId',
data: d,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: testFunc,
error: errFunc
complete:function(){
$(".VoteUp").removeAttr("disabled");
}
});
});
function testFunc(result, userContext, methodName) {
if (result.d[0] == "true") {
$this.val("added");
}
else {
$this.val("deleted");
}
}