how to pass an array of strings from jQuery to controller - c#

How can I pass an array of strings to a controller in asp.net mvc4?
Here is my code
jQuery:
function FnSaveAnalyses(){
var checked = [];
for (var i in checkedIds) {
if (checkedIds[i]) {
checked.push(i);
}
}
alert(checked); // it shows all the records without problem
var url = urlBiologieDemande + "Save";
$.post(
url,
data = { values: checked},
traditional= true,
success = function (data) {
DataSaved();
});
}
Controller
public ActionResult save(string[] values)
{
//Traitement
}
When debugging, I get null values.

POST IT AS JSON array.
var checked = [];
for (var i in checkedIds) {
if (checkedIds[i]) {
checked.push(i);
}
}
var url = urlBiologieDemande + "Save";
$.ajax({
type: 'Post',
dataType: 'json',
url: url ,
data: JSON.stringify(values:checked),
contentType: 'application/json; charset=utf-8',
async: false,
success: function (data) {
}
});
then get the JSON in the Controller
and Parse it ..
see this

Related

JQuery ajax success never run

i have this jquery code, sending items to controller and download from controller, everything is fine
downloads is fine, i check response from in Chrome Network Tab is okay. but success function never run after process done. (i'm using async:false; already)
$(document).on('click', '#baslat', function (e) {
var token = $("#token").val();
var islemler = [];
var secililer = [];
$.each($("input[class='cc']:checked"), function () {
var islem = {};
islem.IslemTuru = $(this).attr("id");
islemler.push(islem);
});
$.each($("tr[class='sec']"), function () {
if ($(this).children('td:eq(1)').children("input[type='checkbox']").prop('checked')) {
var beyan = {};
beyan.Id = $(this).attr("id");
beyan.TahakkukId = $(this).data("id");
beyan.KisaKod = $(this).children('td:eq(2)').html();
beyan.BeyannameTuru = $(this).children('td:eq(4)').html();
beyan.Ay = $(this).children('td:eq(5)').html().substring(8, 10);
beyan.Yil = $(this).children('td:eq(5)').html().substring(11, 16);
secililer.push(beyan);
}
});
$.ajax({
url: '/Ebeyan/BeyanAl',
type: "POST",
dataType: "string",
async: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ secililer, islemler, token }),
success: function (data) {
$("#mesaj").html(data);
alert("done.");
}
});
});
The controller is here. I have to use Thread.Sleep (1000) in the method. because the server on which I want to download files wants 1 second to pass between each request.
public async Task<string> BeyanAl(List<Beyanname> secililer, List<Islem> islemler, string token)
{
bool indir = true;
bool yazdir = false;
bool gonder = false;
foreach (var islem in islemler)
{
if (islem.IslemTuru =="cbyazdir")
{
yazdir = true;
}
if (islem.IslemTuru == "cbgonder")
{
gonder= true;
}
}
foreach (var GelenBeyan in secililer)
{
string YolAdi = YolHazirla(GelenBeyan);
string DosyaAdi = DosyaAdiHazirla(GelenBeyan);
await dosyaindir(token, YolAdi + "/" + DosyaAdi, "Beyan", GelenBeyan.Id, "");
await dosyaindir(token, YolAdi + "/" + DosyaAdi, "Tahakkuk", GelenBeyan.Id, GelenBeyan.TahakkukId);
}
return "İndirildi";
}
here is chrome response screens
r1
r2
There is no 'string' data type in ajax datatypes make it json or text
$.ajax({
url: '/Ebeyan/BeyanAl',
type: "POST",
dataType: "string", <-- make it json or text
async: false,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ secililer, islemler, token }),
success: function (data) {
$("#mesaj").html(data);
alert("done.");
}
});

Sending object to a controller in asp.net mvc using ajax

I have issue with sending object contains array to a controller
this is my js code
var messageId = 0;
function DraftMessage()
{
var to = [];
var i = 0;
$('#to option:selected').each(function (index, element) {
to[i++] = $(element).val();
});
console.log(to);
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage", "Activities")",
datatype: "json",
traditional: true,
async: false,
data: { "id": messageId, "To": to, "Title": $("#title").val(), "Project": $("#project").val(), "AreaId": $("#areaId").val(), "Body": $("#messageBody").val() },
beforeSend: function () { }
}).done(function (Id) {
console.log(Id);
messageId = Id;
});
}
$("input, select, textarea").change(function () { DraftMessage(); });
var contents = $('.note-editable').html();
$(".compose-message").on("blur", ".note-editable", function () {
if (contents != $(this).html()) {
DraftMessage();
contents = $(this).html();
}
});
and this is my controller side
public int DraftMessage(message draftMessage, HttpPostedFileBase[] files = null)
{
return new MessageActions().DraftMessage(draftMessage);
}
my issue is that the ajax request always send the to array as null, I do not know what is wrong so could anyone help me to resolve this issue.
Can you change your request and use
dataType: "json",
contentType: "application/json;charset=utf-8",
This should work. Please let me know.
Try this. Push your object to array and send it as Json.
array.push({yourobject datas here})
$.ajax({
type: "POST",
url: '/DraftMessage/Activities',
contentType: 'application/json',
data: JSON.stringify(array),
success: function (d) {
..
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
Convert your controller function's return type to JSonResult.
Hope helps.
do you want upload file using ajax ?!!
use the normal usage of form not the Ajax.BeginForm then in form submit event
write your code like this:
$('#Form').submit(function () {
var xhr = new XMLHttpRequest();
var fd = new FormData();
var file = $('#Image').val();
if (file) {
var fname = $('#Image')[0].files[0].name;
if (CheckFile(file)) {
var uploadFile = document.getElementById('Image').files[0];
var myArray = [];
myArray.push(uploadFile);
if (myArray.length > 0) {
for (var i = 0; i < myArray.length; i = i + 1) {
fd.append("File1", myArray[i]);
}
}
}
else {
return false;
}
}
fd.append("ID", messageId);
fd.append("Title", $('#Title').val());
fd.append("Project", $('#Project').val());
fd.append("AreaId", $('#AreaId').val());
fd.append("Body", $('#messageBody').val());
var form = $('#Form');
var token = $('input[name="__RequestVerificationToken"]', form).val();
fd.append("__RequestVerificationToken", token);
xhr.open("POST", "/ControllerName/Action/", true);
xhr.send(fd);
xhr.addEventListener("load", function (event) {
if (event.target.response != "OK") {
OnFail(event.target.response);
}
else {
OnSuccess(event);
}
}, false);
return false;
})
server side in controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult actionName(Model pModel){
HttpPostedFileBase File = Request.Files["File1"];
if (File != null && File.ContentLength != 0){
//do what you want
return Content("OK");
}
else{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Content("Error Messages", System.Net.Mime.MediaTypeNames.Text.Plain);
}
}
You can try a different approach. You can serialize your entire form by doing something like this:
var formdata = $("#frmEmailInfo").serialize();
and then post it to the Controller:
$.ajax(
{
type: "POST",
data: formdata,
dataType: 'json',...

getting error on passing string as json object in ajax jquery

I'm trying to pass a string in code behind method using ajax jquery but getting a stupid error. If I pass integer only then it works fine but in case of string it's not working
this is what i've tried
csharp code
public static string GetQuickVD(string key)
{
return key.ToString();
}
jquery
$(document).ready(function () {
GetQuickVL();
});
function GetQuickVL() {
var Nid = new Array();
for (var key in localStorage) {
if (key.substring(0, 4) == "vhs-") {
Nid += key.replace('vhs-', '') + ",";
}
}
$.ajax({
type: "POST",
url: "QuickViewList.aspx/GetQuickVD",
data: '{key: ' +'345,' + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.response);
},
error: function (response) {
alert(response.error);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
use like this
data: {key: "345" }
You can also use like,
type: "GET",
url: "QuickViewList.aspx/GetQuickVD?key=355",
Edit
data: JSON.stringify({"key": "345"}),

MVC post with data and return json data

I have a controle like this
public JsonResult GetSizes(long Id)
{
try
{
//get some data and filter y Id
}
catch (Exception ex) { }
return Json(//data);
}
I need to get that by following json by ajax request
var sizes = [];
$.ajax({
type: 'POST',
async: false,
data: { 'Id': selectedId },
url: "/<Controler name>/GetSizes",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
return false;
},
success: function (result) {
if (result.Result != null) {
if (result.Result.length > 0) {
sizes = result;
}
}
}
});
But this give me an Server error. How can i fix this.
replace your
url: "/<Controler name>/GetSizes",
by
url: "#Url.Action("GetSizes", "Controller_Name"),
and is you Ajax will have to be
async: false?
then try to use this as your Action
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetSizes(long Id)
{
try
{
//get some data and filter y Id
}
catch (Exception ex) { }
return Json(//data);
}
Also, try to put a break point on your action and see in debug mode if your Ajax reaches your Action.
this my demo, you can do the same:
$.ajax({
url: '#Url.Action("CheckCity", "BookingStarts")',
data: { packageId: packageid, cityId: valuecities[valuecities.length - 1] },
type: 'POST',
dataType: 'json',
success:
function(result) {
if (result.Status == true) {
$('#CheckoutDateHotel_#item.CityId').val(result.Date);
}
}
});
in controller :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CheckCity(int packageId, int cityId)
{
var packageCityModel = PackageDetails.GetPackageCitiesByPackageId(packageId).OfType<HMSService.PackageCity>();
var package = new PackageReservationMasterDal();
var itemPackage = package.GetPackageDetailByPackageId(packageId);
var result = "";
var city = packageCityModel.FirstOrDefault(x => x.CityId == cityId);
if (city != null)
{
result = itemPackage.TravelDateFrom.AddDays(city.NoOfNights).ToShortDateString();
}
return Json(new { Status = true, Date = result });
}
See the problem here is that you have not stringified your Data Transfer Object(DTO).
A cleaner approach will be this.
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/json3/3.3.0/json3.js"></script>
<script type="text/javascript">
var sizes = [];
var DTO = { 'Id': selectedId };
$.ajax({
type: 'POST',
async: false,
data: JSON.stringify(DTO),
url: "#Url.Action("GetSizes", "Home")",
dataType: 'json',
contentType: 'application/json'
}).done(function(result) {
if (result.Result != null) {
if (result.Result.length > 0) {
sizes = result;
}
}
}).fail(function(xhr) {
alert('Error: ' + xhr.statusText);
return false;
});
</script>
Please note the use of
JSON.stringify
#Url.Action helper
jqXHR.done(function( data, textStatus, jqXHR ) {});
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
Also you are using async=false which I guess is to grab all the sizes before exiting from the function. jQuery.deferred will be an interesting read.

MVC JsonResult Method not accepting parameter

I have an MVC JsonResult Method that accepts one string parameter:
public JsonResult GetDestinations(string countryId)
{
List<Destination> destinations = new List<Destination>();
string destinationsXml = SharedMethods.GetDestinations();
XDocument xmlDoc = XDocument.Parse(destinationsXml);
var d = from country in xmlDoc.Descendants("Country")
from destinationsx in country.Elements("Destinations")
from destination in destinationsx.Elements("Destination")
where (string)country.Attribute("ID") == countryId
select new Destination
{
Name = destination.Attribute("Name").Value,
ID = destination.Attribute("ID").Value,
};
destinations = d.ToList();
return Json(new JsonResult { Data = destinations}, JsonRequestBehavior.AllowGet);
}
With a jquery method calling the method:
//Fetch Destinations
$("#Country").change(function () {
var countryId = $("#Country > option:selected").attr("value");
$("#Destination").html("");
$("#Resort").html("");
$("#Resort").append($("<option></option>").val(0).html("---Select---"));
$.ajax({
type: "POST",
traditional: true,
url: "/Destinations/GetDestinations",
data: "{countryId:'" + countryId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
BindDestinationSelect(msg)
}
});
});
However, the JsonResult seems to only receive a null parameter. Even though Firebug is showing that a parameter is being passed:
JSON
countryId
"11"
Source
{countryId:'11'}
Any ideas? Thanks
I think the problem is in how you are actually passing the data, you are doing so as a string:
data: "{countryId:'" + countryId + "'}",
When in reality, you should be using a structure on the client side;
data: { countryId: countryId },
jQuery should be able to handle passing the id correctly then. As you are doing it now, it is trying to send JSON to the server, which is not what MVC is expecting, it's expecting a POST with name/value pairs.
You might also want to consider the jQuery Form Plugin, as it makes serializing your Javascript structures into POST data very easy.
Ah, after much searching I've discovered the reason why it fails.
Nothing to do with malformed JSON etc, but rather the fact that the controller method doesnt know what to expect if you try to pass it JSON values:
http://www.c-sharpcorner.com/Blogs/BlogDetail.aspx?BlogId=863
So in my case, I've just elected to pass it a single string value.
$("#Country").change(function () {
var countryId = $("#Country > option:selected").attr("value");
$("#Destination").html("");
$("#Resort").html("");
$("#Resort").append($("<option></option>").val(0).html("---Select---"));
$.ajax({
type: "POST",
traditional: true,
url: "/Destinations/GetDestinations",
data: "countryId=" + countryId,
success: function (msg) {
BindDestinationSelect(msg.Data)
}
});
Here I suggest you to decorate your action with HttpPost attribute
Like :-
[HttpPost]
public JsonResult GetDestinations(string countryId)
{
List<Destination> destinations = new List<Destination>();
string destinationsXml = SharedMethods.GetDestinations();
XDocument xmlDoc = XDocument.Parse(destinationsXml);
var d = from country in xmlDoc.Descendants("Country")
from destinationsx in country.Elements("Destinations")
from destination in destinationsx.Elements("Destination")
where (string)country.Attribute("ID") == countryId
select new Destination
{
Name = destination.Attribute("Name").Value,
ID = destination.Attribute("ID").Value,
};
destinations = d.ToList();
return Json(new JsonResult { Data = destinations}, JsonRequestBehavior.AllowGet);
}
public JsonResult BindAllData(string Userid)
{
List<VoteList> list = new List<VoteList>();
var indexlist = db.TB_WebSites.ToList();
int i = 0;
var countlist = db.Tb_Votes.ToList();
var VCountList = db.Tb_Votes.ToList();
foreach (TB_WebSites vt in indexlist)
{
bool voted = false;
}
return Json(new { List = _list });
}
function DataBind() {
$("#LoadingDatas").show();
var userid = $("#FBUserId").text();
//alert('Data : ' + userid);
var InnerHtml = "";
$.ajax(
{
url: '/Gitex/BindAllData/',
type: 'POST',
data: { "Userid": userid },
dataType: 'json',
async: true,
success: function (data) {
//alert('Done');
//alert(data.List.length);
for (var i = 0; i < data.List.length; i++) {
});
}
Try this, it worked for me
jQuery function
success :function(Destinations)

Categories