I want to update my chart according to user date selection. here i am using chart js. So i want to pass from date and to date value using Ajax to controller so that i can do data filters. But the problem is that the dates are not submitted to controller action.Please guide me where i have missed.
i have tried many links too but is not helping me.
Post datetime to controller
this is also not helping.
Here is my Script
<script>
function SendDates() {
var ListOfDates = [];
ListOfDates.push($("#fromDate").val());
ListOfDates.push($("#endDate").val());
dates = JSON.stringify({ 'ListOfDates': ListOfDates });
alert(dates)
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: "POST",
url: "/dashboard/sendDates",
data: dates ,
success: function (data) {
if (data.status == "successfull") {
alert("Dates were sent successfully ");
} else {
alert("Dates werenot sent successfully ");
}
},
error: function (error) {
console.log(error);
}
})
}
</script>
and this is controller
[HttpPost]
public JsonResult sendDates(DateTime receivedDates) {
DateTime dates = receivedDates;
Debug.WriteLine(" Date is:"+ dates );
return new JsonResult { Data = new { status = "successfull" }
};
}
when i change the data type DateTime to String in controller i get success message but seeing debug output there there is blank.
[HttpPost]
public JsonResult sendDates(String receivedDates) {
var dates = receivedDates;
Debug.WriteLine(" Date is:"+ dates );
return new JsonResult { Data = new { status = "successfull" } };
}
Related
I'm wondering how to display a succes or error message on succes or fail by a controller action in my MVC project with bootstrap. For example I got the following action:
Input:
Javascript method to send data to controller:
//Sends data filled in in modal to backend.
$(document).ready(function () {
$("#btnSubmit").click(function () {
var datastring = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "/ApiBroker/AddApi",
dataType: 'json',
data: datastring,
});
$('#myModal').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
})
})
Controller method:
[HttpPost]
public ActionResult AddApi(ApiRedirect model)
{
var data = model;
try
{
List<ApiRedirect> list = dbProducts.ApiRedirects.ToList();
int companyID = dbProducts.Companies.Where(x => x.CompanyName == model.Company.CompanyName).FirstOrDefault().CompanyID;
int mappingID = dbProducts.MappingNames.Where(x => x.Name == model.MappingName.Name).FirstOrDefault().MappingID;
ApiRedirect api = new ApiRedirect();
api.ApiName = model.ApiName;
api.CompanyID = companyID;
api.ApiURL2 = model.ApiURL2;
api.MappingID = mappingID;
api.ResponseType = model.ResponseType;
dbProducts.ApiRedirects.Add(api);
dbProducts.SaveChanges();
return View ();
}
catch (Exception ex){
throw ex;
}
}
If the method AddUser added the user into my database I want to display a error message, and if the user was not added I want to display a error message. I dont know how to achieve this, any suggetions?
Thanks in advance!
UPDATE
So the alert works but the POST call is getting the following internal server error:
Firstly you ajax needs to be updated to use a success or failure
$.ajax({
type: 'POST',
url: "/ApiBroker/AddApi",
data: datastring,
dataType: 'json',
success:
function(data){
//... put your logic here
},
error:
function(){ alert('error'); }
});
Secondly you need to update your controller action to return a IHttpActionResult where you can specify a Response message.
If you look at this
HttpResponseMessage
I need to get an id from the URL , comment value from textbox, save it to database and show on page with ajax.
Im not sure how should look correct syntax in my controller and ajax function.
Controller
[HttpPost]
public JsonResult AddComment(int id, string comment)
{
if (ModelState.IsValid)
{
return Json(true); // what should be here
}
return Json(true);
}
Ajax
$('#submit').click(function () {
$.ajax({
url: '/Form/AddComment',
method: 'POST',
data: {
id: 4, //how to get id from url?
comment: 'test' //how to get textbox value?
},
success: function (data) {
console.log(data)
},
error: function (a, b, c) {
console.log('err')
}
})
});
this just show me that it work but i dont know how to move forward
Based upon your requirement, you would have to do the appropriate form handling at client side in order to get your variables like id and comment. You can use strongly typed model binding to get your form values and process them on submit or you can use JavaScript techniques to process your form variables. To extract out id from a URL, you can use a Regular Expression or other JavaScript string parsing techniques. I am giving you a simple example of getting your id from a URL and comment from a text box using JavaScript:
Your input control would look like:
<input type="text" id="commentBox" name="Comment" class="form-control" />
In order to achieve your desired functionality using AJAX to POST your form variables to controller, refer to the following code snippet:
AJAX:
<script type="text/javascript">
var url = 'http://www.example.com/4'; //Example URL string
var yourid = url.substring(url.lastIndexOf('/') + 1);
var yourcomment= document.getElementById('commentBox').value;
var json = {
id: yourid, //4
comment: yourcomment
};
$('#submit').click(function (){
$.ajax({
url: '#Url.Action("AddComment", "Form")',
type: "POST",
dataType: "json",
data: { "json": JSON.stringify(json)},
success: function (data) {
console.log(data)
},
error: function (data) {
console.log('err')
},
});
};
</script>
And you can get your values in your Controller like this:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult AddComment(string json)
{
if (ModelState.IsValid)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
string id= jsondata["id"];
string comment=jsondata["comment"];
// Do something here with your variables.
}
return Json(true);
}
My solution looks like this:
controller:
[HttpPost]
public JsonResult AddComment(int id_usr,string comment)
{
if (ModelState.IsValid)
{
Comments kom = new Comments();
kom.DateComment = DateTime.Now;
kom.Id_usr = id_usr;
kom.Comment = comment;
db.Comments.Add(kom);
db.SaveChanges();
return Json(kom);
}
return Json(null);
}
View
var url = window.location.pathname;
var idurl = url.substring(url.lastIndexOf('/') + 1);
$('#submit').click(function () {
console.log('click')
$.ajax({
url: '/form/AddComment',
method: 'POST',
data: {
comment: $("#Comments_Comment").val(),
id_usr: idurl,
},
success: function (data) {
console.log(data),
thank you all for guiding me to the solution
I get a json result from an javascript api query(no problems, valid json) and I would like to insert it into mongoDb.
My json string:
{"data":[{"accessible_wheelchair":true,"address":"181 Washington St","attire":"casual","category_ids":[344],"category_labels":[["Social","Food and Dining","Ice Cream Parlors"]],"country":"us","cuisine":["Ice Cream","Frozen Yogurt","Bagels","Deli","Donuts"],"factual_id":"403b11e4-c383-4305-8ba1-96aa6339eaba","hours":{"sunday":[["11:00","22:00"]],"saturday":[["11:00","22:00"]],"tuesday":[["11:00","22:00"]],"friday":[["11:00","22:00"]],"thursday":[["11:00","22:00"]],"wednesday":[["11:00","22:00"]],"monday":[["11:00","22:00"]]},"hours_display":"Open Daily 11:00 AM-10:00 PM","latitude":42.707169,"locality":"Boxford","longitude":-71.066385,"meal_deliver":false,"name":"Benson Ice Cream","open_24hrs":false,"parking":true,"payment_cashonly":false,"postcode":"01921","price":1,"rating":4.5,"region":"MA","tel":"(978) 352-2911","website":"http://bensonsicecream.com/","wifi":false},{"accessible_wheelchair":true,"address":"256 Georgetown Rd","address_extended":"Unit 5","attire":"casual","category_ids":[363],"category_labels":[["Social","Food and Dining","Restaurants","Pizza"]],"country":"us","cuisine":["Pizza","Cafe","Sandwiches","Subs"],"factual_id":"05e95c81-1125-447b-a500-84e0d380540d","fax":"(314) 423-3377","hours":{"sunday":[["11:00","21:00"]],"saturday":[["11:00","22:00"]],"tuesday":[["11:00","21:00"]],"friday":[["11:00","22:00"]],"thursday":[["11:00","21:00"]],"wednesday":[["11:00","21:00"]],"monday":[["11:00","21:00"]]},"hours_display":"Mon-Thu 11:00 AM-9:00 PM; Fri-Sat 11:00 AM-10:00 PM; Sun 11:00 AM-9:00 PM","latitude":42.697431,"locality":"Boxford","longitude":-70.988191,"meal_cater":true,"meal_deliver":true,"meal_takeout":true,"name":"Boxford House of Pizza","open_24hrs":false,"parking":true,"payment_cashonly":false,"postcode":"01921","price":1,"rating":4.5,"region":"MA","tel":"(978) 887-2212","website":"http://www.bostonrestaurantgroup.com","wifi":false}],"included_rows":2,"total_row_count":2}
I post the json string(arrayString) to a C# controller with ajax.
$.ajax({
url: '/Place/CreateMany',
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify(arrayString),
success: function (valid) {
if (valid) {
alert("success ");
} else {
alert("failure" + arrayString);
}
}
});
The controller errors out with a vague 500 internal server error.
[HttpPost]
public ActionResult CreateMany(string arrayString)
{
JObject jObject = JObject.Parse(arrayString);
JToken placeObj = jObject["data"];
foreach (string data in placeObj)
{
//have a working model defined called PlaceModel
//works with insertOne
var document = BsonSerializer.Deserialize<PlaceModel>(data);
//I am using a working repo(InsertPlace) that uses MongoDB method "insertOne"
//I would like to use a new repo that uses "insertMany"
this._places.InsertPlace(document);
}
return RedirectToAction("List", _places.SelectAll());
}
Not sure what to do to go from json string array of more than one to a single object of my model type (PlaceModel)
This is my first post, so please go easy, but I am open to suggestions.
Veeram was correct. I needed to use BSON serialization not JSON.
[HttpPost]
public void CreateMany(string jsonString)
{
//sets up mongo connection, DB and collection
var Client = new MongoClient();
var DB = Client.GetDatabase("PlacesDb");
var collection = DB.GetCollection<PlaceModel>("PlaceCollection");
if (jsonString != null)
{
IList<PlaceModel> documents = BsonSerializer.Deserialize<IList<PlaceModel>>(jsonString);
collection.InsertMany(documents);
}
}
On the ajax post, I had to add datatype: 'json' and pass my json string as an array jsonString:jsonString with jsonString in [] brackets
self.saveToMongoDB = function (jsonString) {
$.ajax({
url: '/Place/CreateMany',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({ jsonString: jsonString }),
success: function (valid) {
if (valid) {
alert("success " + jsonString);
} else {
alert("failure" + jsonString);
}
}
});
};
I am trying as the title says to return a Json message from the Controller to the View after it validates.
I have made a breakpoint, and I know that the code works from Controller side, and that my JavaScript calls with success the ActionResult now. How do I display that message in the View?
There are two buttons, stamp in and stamp out. If the user stamps in twice, it should get a message, same with stamp out. I have two ActionResults who are indentical except some message and string changes.
Controller:
[HttpPost]
public ActionResult CreateStamp(Stamping stampingmodel)
{
var validateMsg = "";
stampingmodel.Timestamp = DateTime.Now;
stampingmodel.StampingType = "in";
if (stampingmodel.User == null || ModelState.IsValid)
{
var idValidated = db.Users.Find(model.UserId);
if (idValidated != null)
{
var stamp =
db.Stampings.Where(s => s.UserId == stampingmodel.UserId)
.OrderByDescending(s => s.Timestamp)
.FirstOrDefault();
if (stamp.StampingType == stampingmodel.StampingType)
{
if (stampingmodel.StampingType == "in")
{
validateMsg = "Stamped Twice In A Row!";
}
}
else
{
if (stampingmodel.StampingType == "in")
{
validateMsg = "Stamped In, Welcome.";
}
}
}
db.Stampings.Add(stampingmodel);
db.SaveChanges();
}
return Json(new {Message = validateMsg });
JavaScript:
$(document).ready(function () {
$("#stampInBtn").click(function () {
var userId = $("#userId").val();
$.ajax({
url: "ComeAndGo/CreateStamp",
type: "POST",
dataType: "json",
data: {
userId: userId,
}
});
});
View:
<input type="text" id="idUser" class="form-control" />
<br />
<input type="submit" value="IN" id="stampInBtn" />
I have more code inside the View of course; divs, head, body, title and scripts. But it's perhaps a little irrelevant.
What should I do to successfully show those messages?
Regards.
Add a success function to the ajax call
$.ajax({
url: "ComeAndGo/CreateStamp",
type: "POST",
dataType: "json",
data: { userId: userId },
success: function(data) {
// data contains the value returned by the server
console.log(data);
}
});
So if the controller returns
return Json("This is a message");
the value of data will be "This is a message". Note the return value can be a complex type or a partial view
You are getting the value of $("#userId"), but your input has an id of idUser.
Try making your input:
<input type="text" id="userId" class="form-control" />
Also it would be a good idea to provide your Stamping model structure as it seems that you only pass the user id in your post and nothing else.
Change your javascript code as following:
$(document).ready(function () {
$("#stampInBtn").click(function () {
var userId = $("#userId").val();
$.ajax({
url: "ComeAndGo/CreateStamp",
type: "POST",
dataType: "json",
data: {
userId: userId,
},
success: function(data) {
var objData= jQuery.parseJSON(data);
alert(objData.Message );
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
});
I'm developing an online application of tennis club management... (MVC 3, Entity Framework Code first,...)
I've an Interface that allows the user to consult the available tennis court :
In my "AvailableCourtController", I've a function which return the tennis courts :
[HttpPost]
public JsonResult GetTennisCourt(DateTime date)
{
var reservations = db.Reservations.Include(c => c.Customer);
foreach (var reservation in reservations)
{
//Verify that a court is available or not
if (reservation.Date ==date)
{
if (date.Hour > reservation.FinishTime.Hour || date.Hour < reservation.StartTime.Hour)
{
var id = reservation.TennisCourtID;
TennisCourt tennisCourt = (TennisCourt) db.TennisCourts.Where(t => t.ID == id);
tennisCourt.Available = true;
db.Entry(tennisCourt).State = EntityState.Modified;
db.SaveChanges();
}
else
{
var id = reservation.TennisCourtID;
TennisCourt tennisCourt = (TennisCourt) db.TennisCourts.Where(s => s.ID == id);
tennisCourt.Available = false;
db.Entry(tennisCourt).State = EntityState.Modified;
db.SaveChanges();
break;
}
}
}
var courts = from c in db.TennisCourts
select c;
courts = courts.OrderBy(c => c.ID);
return Json(courts, JsonRequestBehavior.AllowGet );
}
So, I would like to change the color of my label if the tennis court is busy or free... For that I use "Ajax":
"View" (What I've tried to make)
<input id="datePicker" type= "text" onchange="loadCourts"/>
<script type="text/javascript">
$('#datePicker').datetimepicker();
</script>
<script type="text/javascript">
function loadCourts() {
var myDate = $('#datePicker').value();
$.ajax({
url: ("/AvailableCourt/GetTennisCourt?date=myDate "),
success: function (data) {
alert('test');
//change label's color
}
});
}
</script>
I never get the message "test"... So I have make something wrong with my Ajax function or my controller's method... My goal is to get the tennis court, check if they're free or not and change color in red if busy, and in green if free...
Can you help me to find what I'm doing wrong please? Sorry :( But I'm a beginner with Ajax...
This line is not passing a date in the querystring:
url: ("/AvailableCourt/GetTennisCourt?date=myDate "),
should be:
url: ("/AvailableCourt/GetTennisCourt?date=" + myDate),
EDIT: Also you're not getting the value correctly:
var myDate = $('#datePicker').value();
should be:
var myDate = $('#datePicker').val();
Your datetimepicker() call has to occur inside of a document.ready. Here is the corrected code:
<input id="datePicker" type= "text"/>
<script type="text/javascript">
$(document).ready(function () {
$('#datePicker').datetimepicker();
$('#datePicker').change(loadCourts);
});
function loadCourts() {
var myDate = $('#datePicker').val();
$.post({
data: "{ 'date' : " + myDate + " }",
url: (#Url.Action("AvailableCourt", "GetTennisCourt"),
success: function (data) {
alert('test');
//change label's color
}
});
}
</script>
}
Your url is wrong :-)
Should be:
$.ajax({
url: "/AvailableCourt/GetTennisCourt?date="+myDate, // without ( )
success: function (data) {
alert('test');
//change label's color
}
});
A more verbose AJAX call:
$.ajax({
type: 'POST',
data: "{ 'date' : " + myDate + " }",
url: '/AvailableCourt/GetTennisCourt',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
timeout: 8000, // 8 second timeout
success: function (msg) {
},
error: function (x, t, m) {
if (t === "timeout") {
HandleTimeout();
} else {
alert(t);
}
}
});
I agree with #CAbbott that your URL was not created correctly. But with date values (and multiple query string values in general), you may be better off adding your date parameter in a data object literal in your ajax call:
function loadCourts() {
var myDate = $('#datePicker').val();
$.ajax({
url: ("/AvailableCourt/GetTennisCourt"),
data: { date: myDate },
success: function (data) {
alert('test');
//change label's color
}
});
}
jQuery will append your data onto the querystring for you and format it appropriately.
From the jQuery API docs:
The data option can contain either a query string of the form
key1=value1&key2=value2, or a map of the form {key1: 'value1', key2:
'value2'}. If the latter form is used, the data is converted into a
query string using jQuery.param() before it is sent.