Using ajax to update list. - javascript

I am currently trying to update a list of duties after the user has posted a new duty. I am trying to use Ajax doing this. However I am not shure how to use ajax for posting to my controller and then add to my list. How do I use my datafield in my ajax method and how do I update my list?
My controller:
[HttpPost]
Public ActionResult CreateDuty(PartialViewModel d)
{
db.DutiesTable.Add(d.OneDuty);
db.SaveChanges();
pv.DutyList = db.DutiesTable.ToList();
return View("Index");
}
My Ajax method:
<script>
$('#getDuty').click(function () {
$.ajax({
type: 'POST',
url: "/Home/CreateDuty",
data: {d : d}
}).success(function (data) {
alert(data + status);
});
});
</script>

Not enough information.
Where did d come from and what is it (javascript).
For your EF code I assume DutiesTable does NOT contain PartialViewModel's so there is a mapping that needs to happen there between the view model and EF model classes.
[HttpPost]
Public ActionResult CreateDuty(DutyViewModel d)
{
Duty newduty = new Duty(){ /*map values from d to fields here*/}
db.Duties.Add(newduty);
db.SaveChanges();
return View("Index");
}
Once you have your data posting over the controller and saving with EF you need to decide on if your javascript needs a copy of the updated entity (mapped back to a PartialViewModel most likely or if a simple success/fail message is enough and do what it needs to on that side.
I don't know what you mean here: "and then add to my list" - what list?

Related

How do I make AJAX grab the data from the controller in MVC?

So, I have this AJAX call and what I want to do is for the controller to return the string as a JSON object back to the view where my ajax call is. Now here's the thing. I don't know how to do it and which class would help me do it. Everything I've tried doesn't work at all. My question is when I use the $.post method how do I make AJAX "grab" the data back from the controller?
Since people comment on my Javascript, I don't mind that, I'll fix it later. The question is
How do I return anything I want from the controller in MVC? The controller is where I need help
Here's my call:
<script>
$(document).ready(function () {
alert("document ready");
// Attach a submit handler to the form
$("#searchForm").submit(function (event) {
alert("submitsearchForm");
//event.preventDefault();
// Get some values from elements on the page:
var $form = $(this),
query2 = $form.find("input[id='query']").val(),
url = "/umbraco/Surface/SearchDictionarySurface/HandleDictionarySearching/";
alert("query2" + query2);
// Send the data using post
var posting = $.post(url, { query: query2 });
alert(url);
//Put the results in a div
posting.done(function (query2) {
var content = //bla bla bla;
$("#result").empty().append(content);
alert(query2);
});
});
});
</script>
Also, I'm using Umbraco. That's why the surface controller:
using MyUmbraco.Models;
using System.Web.Mvc;
using Umbraco.Web.Mvc;
namespace MyUmbraco.Controllers
{
public class SearchDictionarySurfaceController : SurfaceController
{
// GET: SearchDictionarySurface
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult HandleDictionarySearching(string query)
{
if (!string.IsNullOrEmpty(query))
{
var query2 = Json.parse(query);
//return Json object????
//I NEED HELP HERE
}
else
{
return Json(new
{
redirectUrl = Url.Action("Index", "Home"),
isRedirect = true
});
}
}
}
}
So, to any newbies out there that might need the help I needed (and because I've been looking for this thing for AGES and nobody responds, here's how you do it:
Your JQuery callback function, and your controller must have the same variable. E.g:
Controller:
public JsonResult ExampleName(string query)
{
if (!string.IsNullOrEmpty(query))
{
//YOUR CODE HERE
return Json(yourDataHere);
}
else
{
return Json(new
{
redirectUrl = Url.Action("Index", "Home"),
isRedirect = true
});
}
}
And JQuery callback function:
posting.done(function (data) {
//your callback function here
});
That's the trick for JQuery to know what to "grab" from the controller when it returns it. Make sure you return Json(yourDataHere). In case you're wondering, yes, just write 'data' in the function and it will grab yourDataHere from the controller, by itself.
Also, make sure you either have the AntiForgeryToken in both your form and your controller or in none of them. If you have it in your controller only, it will not let you control everything through JQuery.
There is some issues in your javascript.
Try to follow this pattern :
posting.done(function (response) {
var JSONData = JSON.parse(response);
// do something with your json
// ....
// Then append your results in your div.
$('YOUR DIV SELECTOR').html(THAT YOU WANT TO DISPLAY);
});
If you want to return objects and JSON, use a WebAPI controller rather than a surface controller, which will just return an ActionResult. You can get a Surface controller to return JSON, but you'd be better off using an API controller, as that will return JSON objects by default, which is what I assume you're after?
Here's some documentation for WebAPI controllers!

Minor trouble with AJAX POST method passing to C# MVC controller method

Hello denizens of stackoverflow, I've been debugging a pesky ajax POST method for a bit too long now, and was hoping I could get some input. I have a JavaScript function that collects an array of strings to box up and send off to a controller method of mine, but unfortunately the parameter data is not being sent, and I cannot figure out why.
Here is the JS function:
$.ajax({
url: 'CancelDoc',
method: 'POST',
datatype: 'json',
headers: addAntiForgeryHeader(),
data: { datakeys : DataKeys }
}).done(function (data) {
if (data.status == 0) {
alert("DOCUMENT CANCELLED SUCCESSFULLY");
}
});
To clarify a little:
DataKeys is the array of strings. It is coming through to this point as it should.
Looks something like:
["1432long-crazy4297-jumbled5826string|9000|1|1|NEW",
"1432and2-another03-jumbled1594string|9000|1|1|NEW"]
addAntiForgeryHeader() is an extra client validation method that I add on to all POSTs. The problem should not lie here because I have commented this out to try the call and it still does not pass data.
The C# controller method this goes to:
Note: the code DOES make it this far, the datakeys parameter is null though.
public ActionResult CancelDoc(string[] datakeys)
{
DocObject Doc = new DocObject();
List<string> Datakeys = datakeys.ToList();
foreach (var dk in Datakeys)
{
...
Some model logic here (not even making it here so no worries)
...
}
return Json(new { status = 0 });
}
I have tried:
Data conversion to JSON in numerous ways: ko.mapping.toJS(data), JSON.stringify(data), and literal writing of a JSON object for this.
Stripping the call down to the most basic form: I have tried commenting out the datatype and headers properties. This had a couple more properties before I posted as well.
Any input is greatly appreciated.
The dataKeys payload need to be stringify as :
$.ajax({
//prev code
data: { datakeys : JSON.stringify(DataKeys) }
}).done(function (data) {
//success
});
In the MVC controller, desearlze the json as:
public ActionResult CancelDoc(string[] datakeys)
{
dynamic sourceJson = JsonConvert.DeserializeObject(dataKeys, typeof(object));
DocObject Doc = new DocObject();
List<string> Datakeys = sourceJson.ToList();
}

ASP .NET MVC - Ajax POST action fail

I'm trying to do a simple action with some JavaScript code. I've got some items on a scheduler (DevExpress scheduler component). When I'm double clicking on an appointment (an item then), it should raise an JS function which is the case. My function should get the selected appointment id and pass it to Controller Action. Here is my JS code :
function DoubleClick() {
debugger;
var apt = GetSelectedAppointment(scheduler);
var aptid = apt.appointmentId;
$.ajax({
type: "POST",
url: "/Home/GetAppId",
data: { id: aptid },
dataType: 'json',
success: function () {
alert("ok");
},
error: function () {
alert("error");
}
});
}
And here is my C# code :
[HttpPost]
public JsonResult GetAppId(int id)
{
context = new SchedulingDataClassesDataContext();
DBAppointment app = (from a in context.DBAppointment where a.UniqueID == id select a).FirstOrDefault();
return Json(new {rep = app});
}
As you can see in my JS code, I'm not doing anything special in case of success. However, I never reach the success part. Plus, when I'm looking at the Chrome dev tool (F12), I'm getting that red error message.
POST http://localhost:25206/Home/GetAppId 500 (Internal Server Error)
Anything that I'm doing wrong?
Man, you need to force things as follows
return Json(new {rep = app},"text/json",JsonRequestBehavior.AllowGet);
In addition, mind your navigation properties (if any) in order to avoid circular reference
According to your error your problem somewhere in select your data from DB or creating anonymous object when you try to serialize it to Json. I rewrite your select to simplify it and not creating any anonymous objects when return it from Controller like this:
[HttpPost]
public JsonResult GetAppId(int id)
{
context = new SchedulingDataClassesDataContext();
DBAppointment app = context.DBAppointment.FirstOrDefault(x => x.UniqueID == id);
return Json(app);
}
Does it work like this?
Please remove the name of the property in ajax data and edit that property as below.
function DoubleClick() {
debugger;
var apt = GetSelectedAppointment(scheduler);
var aptid = apt.appointmentId;
$.ajax({
type: "POST",
url: "/Home/GetAppId",
data: aptid,
dataType: 'json',
success: function () {
alert("ok");
},
error: function () {
alert("error");
}
});
}
and edit your controller as follows
[HttpPost]
public JsonResult GetAppId([FromBody]int id)
{
//...
}
Please read this blog post which is a good read and allowed me to understand what's going on.
http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
The original question that I asked
Simple post to Web Api
Try changing the last line of the method to:
return Json(new { rep = app }, JsonRequestBehavior.AllowGet);
You need to tell C# to allow the json to be returned to the client.

MVC 3 jquery ajax post 2 objects

I have a controller action that takes two objects as arguments. I can't get it to work at all they always come back as null. My latest try looks like below. I have tried many other variations. In this case the FormInfo class is a class with 2 properties that are types for Form1 and Form2. I have also tried having the controller take in the two classes as arguments and the data part looked like { form1: form1Data, form2: form2Data } that was not working as well. I also tried using JSON.stringify to form the data with no luck.
Looking in the network monitor I see the data going back to the server it's just the engine that MVC uses to decode the query string to the objects can't handle what I'm passing back.
Thanks in advance for any information!
ClientSide
var formData = $("#form1").serialize();
var formData2 = $("#form2").serialize();
var formInfo = new Object();
formInfo.FormData = formData;
formInfo.FormData2 = formData2;
$.ajax({
url: 'Controller/Action',
type: 'POST',
data: formInfo,
success: function (data) {
//do stuff
}
});
ServerSide
public ActionResult SaveForms(FormInfo formInfo)
{
//Do Stuff here
}
You could use the a JSON request in conjunction with the .serializeArray() jQuery method. Let's suppose that you have the following model:
public class FormInfo
{
public Form1Data Form1Data { get; set; }
public Form2Data Form2Data { get; set; }
}
where Form1Data and Form2Data are some completely arbitrary complex classes. Now on the client we suppose that you have 2 distinct forms (#form1 and #form2 whose input element names match your complex structures in terms of default model binder wire format). Sending an AJAX request and packing the 2 forms together becomes trivial:
var form1Data = {};
$.each($('#form1').serializeArray(), function () {
form1Data[this.name] = this.value;
});
var form2Data = {};
$.each($('#form2').serializeArray(), function () {
form2Data[this.name] = this.value;
});
$.ajax({
url: '#Url.Action("someaction", "somecontroller")',
type: 'post',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
form1Data: form1Data,
form2Data: form2Data
}),
success: function (result) {
// TODO: do something with the result
}
});
And of course the controller action you are POSTing to looks like this:
[HttpPost]
public ActionResult SomeAction(FormInfo formInfo)
{
...
}
I am doing something like this but i have a object and other Formdata to pass my Controller
var discrepancy = self.newCptyReply();
if ($('#UploadFile')[0]) {
var upload = new FormData(),
file = $('#UploadFile')[0].files[0];
upload.append('id', self.globalMessageId());
upload.append('discrepancy', ko.toJSON(discrepancy));
upload.append('doc', file);
}
datacontext.saveCptyToReply(self, upload);
And in controller signature
public ActionResult SaveCptyToReply(Guid id, Trade discrepancy, HttpPostedFileBase doc)
But when it reaches Controller id , doc are ok but discrepancy is null... It has data when funciton is called..
What to do...

Passing JSON objects from javascript to ASP.NET MVC

Hi i have some complex types in javascript and want to pass them to my ASP.NET MVC app, the problem is how? I already added a custom ModelBinder (but i dont see why do i need to do that, unless i need to set some erros). The problem is i have;
var obj =
{
"intvar":"222",
"stringvar" :"31asd",
"datevar":new Date(123),
....
}
How do i pass this object to ASP.NET? via query string and via Post method.
EDIT: Soz for the bad explanation what i want is:
public class SomeObj
{
public int intvar;
public string stringvar;
public DateTime datevar;
}
public class HomeController : Controller
{
public someActionMethod(SomeObj o)
{
}
}
Thkz in advance.
Make an AJAX call:
var json =
{
intvar : 222,
stringvar: '31asd',
datevar: new Date(123)
}
$.ajax({
type: "POST",
url: "<%= Url.Action("handleJson", "<YOUR CONTROLLER NAME>") %>",
dataType: "json",
data: json,
success: function(data) {
alert(data);
}
});
Then your controller method could accept parameters named the same as your json properties:
public ActionResult handleJson(int intvar, string stringvar, DateTime datevar)
{
return Json("I did cool stuff but you can't see it :)");
}
Please see if this answer helps. Look especially at all the attributes that the service class and service method has.
Also this article has some tips this question could use

Categories

Resources