I have a ASP.NET MVC application and I have a few entries on the page that user can change and click Save and I go save those entries. My problem: It works fine for some entries and for other entries it just doesn't go in the controller Save function to do the save.
My code:
function DoSave() {
$("#pisave").attr("disabled", true);
var pid = $("#personid").val();alert(pid);
var firstname = $("#fname").val();alert(firstname);
var lastname = $("#lastname").val();alert(lastname);
var plz = $("#zip").val();alert(plz);
var ort = $("#city").val();alert(ort);
var bday = $("#birthdate").val();alert(bday);
var strasse = $("#street1").val(); alert(strasse);
var emailtext = $("#email").val();alert(emailtext);
var url = "#(Url.Action("SavePersonInfo", "Info"))";alert("URL");
$.ajax({
url: url,
data: { personid: pid,fn: firstname, ln: lastname, email: emailtext, zip: plz, city:ort, birthday: bday, street:strasse },
success: function () {
alert("Update Successful");
$("#pisave").removeAttr("disabled");
},
error: function () {
alert("Update Failed! Check entries.");
$("#pisave").removeAttr("disabled");
}
});
}
All alerts are displayed in all the cases. Only for some it goes to SavePersonInfo and for others it doesn't go in there. Any ideas what might be wrong?? Can it be validation issue for the entries?
The model binder fails to parse your date, change to post:
$.ajax({
type: "POST",
url: url,
data: { personid: pid,fn: firstname, ln: lastname, email: emailtext, zip: plz, city:ort, birthday: bday, street:strasse },
success: function() {
alert("Update Successful");
$("#pisave").removeAttr("disabled");
},
error: function() {
alert("Update Failed! Check entries.");
$("#pisave").removeAttr("disabled");
}
});
Read more about the problems with dates in asp.net-MVC
Note that you can add all the elements a class and use the serialize function:
$.ajax({
type: "POST",
url: url,
data: $('.theClass').serialize(), // <=============
success: function() {
alert("Update Successful");
$("#pisave").removeAttr("disabled");
},
error: function() {
alert("Update Failed! Check entries.");
$("#pisave").removeAttr("disabled");
}
});
Related
My ASP.net controller is receiving null instead of passed in parameters :(
Js function:
function SendFormToController() {
var username = document.getElementById("UsernameField").value;
var email = document.getElementById("EmailField").value;
var password = document.getElementById("PasswordField").value;
var SendJson = {
Username: username,
Email: email,
Password: password
};
console.log(JSON.stringify(SendJson));
$.ajax({
type: "POST",
data: JSON.stringify(SendJson),
url: "Register/Register",
contentType: "application/json"
});
}
Data is present when I console log it. But in the controller, I get - https://prnt.sc/u2mpa6
And it is for every field here
First; Did you add the [HttpPost] attribute on top of your controller method?
Second; If you submit it in 'querystring' format: Username=xx&Password=yy&... and use (HttpGet). Does that work?
If you need to do a POST (and not want to use GET) you can create an object with all your current arguments and use the [FromBody] attribute:
[Route("Register")]
[HttpPost]
public ResultData Register([FromBody] RegisterRequest data) {
//Your logic...
}
And client (JavaScript) side:
let url = 'http://...';
$.post(url, { Username: name, Password: pass, What: ever }, function (result) {
//Do some nice stuff
})
.fail(function (error) {
//Oh no! Show error.statusText
});
I have a simple chat application using Ajax and HTML.
Whenever I load new messages, I want to scroll the div to show the most recent message, so I'm doing the following:
jQuery:
function SendMessage()
{
var clientmsg = $("#comment").val();
var email = $("#email").val();
event.preventDefault();
if (clientmsg != '')
{
$.ajax(
{
type: 'POST',
url: url,
data:
{
email: email,
message: clientmsg
},
success: function (data)
{
// Success means the message was saved
// Call the function that updates the div with the new messages
UpdateChat();
$("#conversation").scrollTop($("#conversation").outerHeight() * 1000);
}
});
}
}
I use this line to scroll the div down to the maximum:
$("#conversation").scrollTop($("#conversation").outerHeight()*1000);
My problem is, it scrolls down to the maximum WITHOUT showing the new messages. It scrolls down till the last message before the new one. Which is weird, because I'm calling it after updating the chat. Here's the function that updates the chat:
function UpdateChat(){
$.ajax({
// URL that gives a JSON of all new messages:
url: "url",
success: function(result)
{
var objects = JSON.parse(result);
$("#conversation").html("");
objects.forEach(function(key, index){
//append the messages to the div
$("#conversation").append("html here");
});
}
});
};
As mentioned in comments, you can use a setTimeout() to let the dom update add give some time before scrolling. See code below:
function SendMessage()
{
var clientmsg = $("#comment").val();
var email = $("#email").val();
event.preventDefault();
if (clientmsg != '')
{
$.ajax(
{
type: 'POST',
url: url,
data:
{
email: email,
message: clientmsg
},
success: function (data)
{
// Success means the message was saved
// Call the function that updates the div with the new messages
UpdateChat();
setTimeout(function() {
$("#conversation").scrollTop($("#conversation").outerHeight() * 1000);
}, 500);
}
});
}
}
Assuming you insert a new element at the bottom, you could use scrollIntoView to make sure the new element is visible:
$.ajax({
// ...
success: function(data) {
var lastElement = $('#conversation :last-child');
lastElement[0].scrollIntoView();
}
});
Try putting the scroll line inside a setTimeout() method to allow about 500ms for things to update before scrolling down.
jQuery:
function SendMessage(){
var clientmsg = $("#comment").val();
var email = $("#email").val();
event.preventDefault();
if (clientmsg != '') {
$.ajax({
type: 'POST',
url: url,
data: {
email: email,
message: clientmsg
},
success: function (data) {
// Success means the message was saved
// Call the function that updates the div with the new messages
UpdateChat();
setTimeout(performScroll, 500);
}
});
}
}
and the scroll function
function performScroll() {
$("#conversation").scrollTop($("#conversation").outerHeight()*1000);
}
I'm using ajax to call a server side function. for some reason, the success is firing but it doesn't get to the function
here is the javascript
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: "Server.aspx/sendEmail",
data: { name: "foo", company: "bar", country: "foo", email: "bar", msg: "bla" },
async: false,
success: function (data) {
var a = 3;
},
error: function (a, b) {
alert("error");
var a = 43;
}
});
});
here is the c#
[WebMethod]
public static string sendEmail(string name, string company, string country, string email, string msg)
{
//somecode here
}
the data message(for some reason it is breaking)
<form method="post" action="./sendEmail?%7b%22name%22%3a%22foo%22%2c%22company%22%3a%22bar%22%2c%22country%22%3a%22foo%22%2c%22email%22%3a%22bar%22%2c%22msg%22%3a%22bla%22%7d" id="form1">
<div>
</div>
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="368A1591" />
Take the following points into account when you are calling an ASP.NET AJAX page methods:
To use ASP.NET AJAX page methods, you need to make a POST request. This is to prevent CSRF
Ensure that the contentType is set to application/json.
Use JSON.stringify to convert the JavaScript object into JSON text.
Your JS code could be something similar to this:
$(document).ready(function () {
var data = { name: "foo", company: "bar", country: "foo", email: "bar", msg: "bla" };
$.ajax({
url: "Server.aspx/sendEmail",
type: "POST",
data: JSON.stringify(data),
async: false,
contentType: 'application/json',
success: function (data) {
//Do something
},
error: function (xhr) {
alert('Request Status: ' + xhr.status
+ ' Status Text: ' + xhr.statusText
+ ' ' + xhr.responseText);
}
});
});
If it still doesn't work, check the statusText for the error.
I am a newbie in Knockout JS. i want to apply validations in KO. i have used plugin knockout.validation.min.js . I have implemented it like this but not working
My View Model
$(document).ready(function myfunction() {
ko.applyBindings(new EmployeeKoViewModel());
})
var EmployeeKoViewModel = function () {
var self = this;
self.EmpId = ko.observable()
self.Name = ko.observable("").extend({ required: { message: "please enter employee name " } });
self.City = ko.observable("").extend({ required: { message: "please enter employee city " } });
self.Employees = ko.observableArray();
//GetEmployees();
var EmpData = {
EmpId: self.EmpId,
Name: self.Name,
City: self.City,
};
function GetEmployees() {
$.ajax({
type: "GET",
url: "/Employee/About",
}).done(function (data) {
self.Employees(data);
}).error(function (ex) {
alert("Error");
});
}
self.save = function () {
var EmployeeKoViewModel.errors = ko.validation.group(self);
if (!EmployeeKoViewModel.errors().length <= 0) {
EmployeeKoViewModel.errors.showAllMessages();
return false;
}
$.ajax({
type: "POST",
url: "/Employee/Save",
data: ko.toJSON(EmpData),
contentType: "application/json",
success: function (data) {
self.EmpId(data.EmpId);
GetEmployees();
},
error: function () {
alert("Failed");
}
});
//Ends Here
};
}
I have created a fiddle it is working when i comment GetEmployees() method but not working with it
At this line
var EmployeeKoViewModel.errors = ko.validation.group(self);
you are trying to create a variable, but the syntax is like creating an object with a property which is of course invalid. In order to fix this you can initialize your object first:
var EmployeeKoViewModel = {};
EmployeeKoViewModel.errors = ko.validation.group(self);
if (!EmployeeKoViewModel.errors().length <= 0) {
EmployeeKoViewModel.errors.showAllMessages();
return false;
}
Here is a working jsFiddle
i want jquery to take a JsonResult from my MVC controller but it does'nt receive any data!
If I put the output into a textfile and enter its link its working so I think my jQuery is fine.
Then I was testing with other browsers like chrome and I saw NOTHING. The requested page was just emtpy.. no errors. Also IE seems to have problems receiving my string.. only firefox displays the string but why?
public JsonResult jsonLastRequests()
{
List<Request> requests = new List<Request>();
while (r.Read())
{
requests.Add(new Models.Request()
{
ID = (int)r[0],
SiteID = r[1].ToString(),
Lat = r[2].ToString(),
City = r[4].ToString(),
CreationTime = (DateTime)r[5]
});
}
r.Close();
return Json(requests);
}
I found out that also if I want to return the JSON as string its not working!
Its working with a string in all browsers now.. but jQuery is still not loading anything
var url = "http://../jsonLastRequests";
var source =
{
datatype: "json",
datafields: [
{ name: 'ID' },
{ name: 'SiteID' },
{ name: 'Lat' },
{ name: 'CreationTime' },
{ name: 'City' },
],
id: 'id',
url: url
};
var dataAdapter = new $.jqx.dataAdapter(source, {
downloadComplete: function (data, status, xhr) { },
loadComplete: function (data) { },
loadError: function (xhr, status, error) { }
});
I fixed my problem by adding:
access-control-allow-origin:*
public HtmlString jsonLastRequests()
{
List<Request> requests = new List<Request>();
while (r.Read())
{
requests.Add(new Models.Request()
{
ID = (int)r[0],
SiteID = r[1].ToString(),
Lat = r[2].ToString(),
City = r[4].ToString(),
CreationTime = (DateTime)r[5]
});
} r.Close();
System.Web.Script.Serialization.JavaScriptSerializer jSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return new HtmlString(jSerializer.Serialize(requests ));}
I have done same approch like this
$.ajax({
type: 'POST',
url: '/home/GetSurvey',
data: {
XmlPath: $("#xmlpath").val()
},
dataType: 'json',
success: function (jsonData) {
jsonStringQuestionaire = jsonData;
LoadSurvey();
},
error: function () {
alert('Error loading ' + id);
}
});
questionaireJsonList = eval(jsonStringQuestionaire);