How to pass large string through ajax call to controller in MVC? - ajax

How to pass large string data (stringified data) through ajax call to controller in MVC?
In my current scenario, my string is 820 KB. In controller, the string is received as [{"Id":"2vwf35f!##qad", .... name:"sdfs"}].
I can find .... in between the string data at controller side.

This what i use to post data using Jquery ajax call to my Codeigniter controller.
You can send large amount of data using this method.
var id=$(".id").val();
var name=$(".name").val();
var formData = {
'id' : id,
'name' : name,
};
$.ajax({
type: 'POST',
url: "<?=base_url()?>ControllerName/saveAjaxdata/",
data: formData,
dataType: "text",
success: function(resultData)
{
console.log(resultData);
}
});

Related

Returning data objects from ajax query to controller

I'm attempting to access data from a form and pass it to a controller in MVC.
I was successful in passing the data when I get the element by ID and pass as string:
This works:
data: JSON.stringify({
'Answer0': $("#Answer0").val(),
'Answer1': $("#Answer1").val(),
'Question0': $("#Question0").val()
}),
However I want to bring the data in as a viewmodel. When I specify the request as:
data: JSON.stringify($('#' + formDiv).serializeObject()),
It will populate the viewmodel, however there are fields that are not bound to the ViewModel that I would like to pass along with the serialized form. I have tried just adding them, but they don't seem to come in if I pass both the serialized form object and the additional string.
function clickedNext(e, formDiv) {
var sURL = '#Url.Action("SurveySave", "Home")'
$.ajax({
url: sURL,
type: "POST",
contentType: 'application/json',
data: JSON.stringify($('#' + formDiv).serializeObject(), { 'Answer0': $("#Answer0").val(), 'Answer1': $("#Answer1").val() }),
success: function (data) {
//$('#InvestigationStatus').html(data);
}
});
Controller
[HttpPost]
public ActionResult SurveySave(SurveyViewModel s, string Answer0, string Answer1)
I feel like you can't put two objects inside of JSON.stringify();
Maybe try something like:
var bothObjects = {
$('#' + formDiv).serializeObject(),
{ 'Answer0': $("#Answer0").val(), 'Answer1': $("#Answer1").val() }
}
...
JSON.stringify(bothObjects),

Retrieve post value in the controller sent by ajax call

I am unable to retrieve value sent as a post through ajax call in cake php controller file
$.ajax({
type: "POST",
url: "share",
data: country,
dataType: "json",
success: function (response) {
if (response.success) {
// Success!
} else {
console.log(response.data, response.code);
}
}
});
I have tried with the below ways of retrieving the data sent in the above code through POST. But none of them worked.
$this->params
$this->data
$_POST[]
$this->request
The url points to the function in the controller page.
Please can any of you let me know how the value can be retrieved.
When submitting data via ajax and you want cake to pick it up in the usual way just use $('whatever').serialize().
if you don't have an actual form to serialize you can fake it by submitting the data as follows:
$.ajax({
...
data: {
data: country
},
...
});
Note how cake generates fields like data[Model][field]. you don't need the Model part but the data part is important.

MVC3 Get Ajax Posted Values

in postback requests when i need posted values i do like this
[HttpPost]
public ActionResult Index()
{
//i need to get values in here not in action method argument
//i know this works but not like this --> ActionResult Index(string Name)
string Name = Request.Form["Name"];
}
but in ajax requests this does not work,,and i cant find where mvc store ajax posted values
Any Suggestions?
I'm a little late to the party, but I will offer an alternative that will allow you to access Request.Form with an Ajax post/form. This was tested in MVC 4 and jQuery 1.9.1.
If the controller's Request.Form is not populating for your Ajax post, it is likely because you are manually serializing and sending the data to the controller with a contentType of application/json (a common scenario).
Here is an jQuery.ajax example that will NOT populate Request.Form on the controller.
// JSON serialized form data.
var data = {"id" : "1234", "name" : "Dave"};
$.ajax({
type: "POST",
url: serviceUrl,
contentType: "application/json",
dataType: "json",
data: JSON.stringify(data || {}),
success: function () { }
});
Changing the contentType will cause the controller to process the post like a form submission.
// Form encoded data. See jQuery.serialize().
var data = "id=1234&name=Dave";
$.ajax({
type: "POST",
url: serviceUrl,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType: "json",
data: data,
success: function () { }
});
You can also leave contentType undefined as application/x-www-form-urlencoded; charset=UTF-8 it is the jQuery default.
I would note that I only used $.ajax to better illustrate what is going on. You could also use $.post, though you will still need to send form encoded data
The ajax posted values won't appear in the request from collection however you can use the ValueProvider infrastructure in MVC to get the your Ajax posted value:
[HttpPost]
public ActionResult Index()
{
Name = ValueProvider.GetValue("Name").AttemptedValue;
}
Or the Request.InputStream contains all the posted data what you can read and deserailize as you want:
[HttpPost]
public ActionResult Index()
{
var serializer = new JavaScriptSerializer();
using (var streamReader = new StreamReader(Request.InputStream))
{
var data = (Dictionary<string,object>)serializer
.DeserializeObject(streamReader.ReadToEnd());
//assuming your posted data looks like this: '{"Name": "test"}'
string name = data["Name"].ToString();
}
}
But I highly recommend that you should not fight against the MVC infrastructure and recive the data as your action paratemer:
[HttpPost]
public ActionResult Index(string name)
{
}

mvc3 partialview doesn't load query string

I have Partial View that is updated with AJAX. The problem is that Partial View needs to take two parameters and one isn't in query string.
this is controller
public ActionResult _Unutrasnjost(string verzijaIme,int bojeId=0)
{
return PartialView(repositoryU.BojeUnutrasnjostVezano.Where(v =>v.VerzijaIme==verzijaIme&&v.BojeId == bojeId).ToList());
}
string verzijaIme is in query string but when the partialview is loaded it tells me that is undefined
int bojeId isnt in query string but when user clicks on button its send by AJAX.
I dont understand why everything is working if I put only one parameter (string or int) and if I put two parameters verzijaIme is undefined?
Its also working if I remove =0 from int bojeId and put that parameter in query string but I cant accept that kind of solution
Any suggestion?
Ajax code
function unutrasnjostData(id) {
var urlclear = '#Url.Action("_Unutrasnjost", "Configurator")' + "?bojeId=" + id;
$.ajax({
cache: false,
type: 'POST',
url: urlclear,
success: function (data) {
$('#meniDesnoIzmjeneUnutrasnjost').html(data);
}
});
}
Looks like you're not passing verzijaIme to partial view at all. You need to extend your unutrasnjostData function:
function unutrasnjostData(id, verzijaIme) {
var urlclear = '#Url.Action("_Unutrasnjost", "Configurator")' + "?bojeId=" + id + "&verzijaIme=" + verzijaIme;
$.ajax({
cache: false,
type: 'POST',
url: urlclear,
success: function (data) {
$('#meniDesnoIzmjeneUnutrasnjost').html(data);
}
});
}
Or, even better, send it in post:
$.ajax({
cache: false,
data: { bojeId: id, verzijaIme: verzijaIme },
type: 'POST',
url: urlclear,
success: function (data) {
$('#meniDesnoIzmjeneUnutrasnjost').html(data);
}
});
Don't confuse the query string from the request to the page with the query string from the AJAX call. Those are two separate requests.

MVC 4 - Sending Model Data via JSON to Nested Partial Using Ajax Call

I have a cshtml page with a partial view. I have an ajax call in that same view retrieving json data based off separate url. I need to pass in the json data into partial. How to do this?
You could have a controller action taking the view model and passing this view model to the partial view:
public ActionResult SomeAction(MyViewModel model)
{
return View(model);
}
and then once you retrieve the JSON data you could invoke this controller action passing the model:
// TODO: The JSON data could come from anywhere
var jsonData = { foo: 'bar' };
$.ajax({
url: '#Url.Action("SomeAction")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(jsonData),
success: function(result) {
// Now update the partial:
$('#someId').html(result);
}
});

Resources