javascript\jQuery:
var items = new Array();
var obj { Begin: "444", End: "end" };
items.push(obj);
items.push(obj);
var request = {
DateStart: $("#DateStart").val(),
mass: items
};
$.post("/Home/Index", request, null,
"json");
C# Mvc Index Controller
public class MyClass
{
public string Begin;
public string End;
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(
string DateStart,
MyClass []mass)
{
System.Diagnostics.Debug.WriteLine(mass[0].Begin);
}
how to execute this code? thanks.
U can't pass mass: items and expect it to be serialized as a JSON array automatically, you will need to either iterate and construct the JSON (bad plan) or use a JSON library(good plan)
Try write code as below:
var option = {
url: '/Home/Index',
type: 'POST',
data: JSON.stringify(request),
dataType: 'html',
contentType: 'application/json',
success: function(result) {
alert(result);
}
};
$.ajax(option);
Related
I am passing an array variable to the controller.
Array from ajax call contains data but after calling the controller it shows count=0.
var url = '#Url.Action("UserRoleCompany_AddUserAccess", "UserRoleCompany")';
$.ajax({
url: url,
data: { userIDs: userIDs, Organisation: Organisation, RoleName: RoleName, userIDsLength: userIDsLength, UserStatus: UserStatus },
cache: false,
type: "POST",
success: function (data) {
location.reload(true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
Controller code below,
public ActionResult UserRoleCompany_AddUserAccess(List<int> userIDs, string Organisation, string RoleName, int userIDsLength,int UserStatus)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
objLMTDAL.UserRoleCompany_AddUserAccess(Organisation, RoleName, userIDsLength, UserStatus);
return RedirectToAction("Index");
}
And below are a screenshot for reference,
You can not pass an array as a parameter in ajax,you can either convert userIDs to a json string or combine them as a string,then pass to the controller side.
More details information can be found at Why the array will not send through the ajax call?
#lucumt
I have tried the same thing with table - selecting the multiple rows from the table and send it to the controller and it is working fine.
Please check below and let me know.
var url = '#Url.Action("UserRoleCompany_UpdateUserAccess", "UserRoleCompany")';
$.ajax({
url: url,
data: { Ids: checkedIds, newUserStatus: UserStatus },
cache: false,
type: "POST",
success: function (data) {
location.reload(true);
},
error: function (reponse) {
alert("error : " + reponse);
}
});
Controller
public ActionResult UserRoleCompany_UpdateUserAccess(List<int> Ids, int newUserStatus)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
string userRoleIds = String.Join(",", Ids);
objLMTDAL.UserRoleCompany_UpdateUserAccess(userRoleIds, newUserStatus);
return RedirectToAction("Index");
//return RedirectToAction("Index", "UserRoleCompany");
}
You can check the live scenario below in screenshots,
Here is my WebAPI POST method which expects BookingDetail and BookingVenue objects:
[HttpPost]
[ValidateUserSession]
public JsonResult CheckBooking(BookingDetail BookingDetail, BookingVenue objBV)
{
try
{
if (BookingDetail != null && objBV != null)
{
bool result = Ibook.checkBookingAvailability(BookingDetail, objBV);
if (result == false)
{
return Json("NotAvailable");
}
else
{
return Json("Available");
}
}
else
{
return Json("Available");
}
}
}
Angular code from where I'm getting the values from UI and making a post passing these 2 objects:
this.checkbookingavailability = function (Book) {
var BookingVenueObj = {
EventTypeID: Book.EventSelected,
VenueID: Book.Venueselected,
GuestCount: Book.NoofGuest,
};
var BookingDetailObj = {
BookingDate: Book.BookingDate
};
var response =
$http({
method: "POST",
url: "/Booking/CheckBooking/",
headers: {
'RequestVerificationToken': $cookies.get('EventChannel')
},
data: { BookingDetail: BookingDetailObj, BookingVenue: BookingVenueObj }
});
return response;
}
Problem is in my WebAPI code, both the objects as null
You can only pass one object in the body so I would recommend you to create a new DTO "BookingDto" for that containing BookingDetail and BookingVenue as member and change the signature of your WebAPI to this:
[HttpPost]
[ValidateUserSession]
public JsonResult CheckBooking([FromBody]BookingDto bookingObj)
You need to serialize JSON object which you are sending to server just by calling JSON.stringify over object.
var response =
$http({
method: "POST",
url: "/Booking/CheckBooking/",
headers: {
'RequestVerificationToken': $cookies.get('EventChannel')
},
data: JSON.stringify({
BookingDetail: BookingDetailObj,
BookingVenue: BookingVenueObj
})
});
return response;
As dear Pankaj mentioned you need to Serialize your data objects with Stringify function in javascript, Also consider that you must mention that this http request contain Application/JSON content. All these can be shown here:
var response =
$http({
method: "POST",
url: "/Booking/CheckBooking/",
headers: {
'RequestVerificationToken': $cookies.get('EventChannel'),
'Content-Type' : 'application/json'
},
data: JSON.stringify({
BookingDetail: BookingDetailObj,
BookingVenue: BookingVenueObj
})
});
return response;
I need to POST a key pair value dictionary to the REST API. I am using NancyFx framework for binding parameters
Server side property:
public Dictionary<string, string> foo { get; set; }
Client side code:
var bar = [];
bar["one"] = "First";
bar["two"] = "Second";
var UserModel = {
someotherpar: "abc",
foo: bar
};
$.ajax({
url: 'myEndpoint',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(UserModel),
success: function (data, textStatus, jqXHR) {
}
});
This was possible with the use of SortedList and not Dictionary.
I am using webapi2 and here is my client side code
var tbody = $('#files-table').find('tbody'); // tbody where all rows exists
var sortOrder = $(tbody).sortable('toArray').toString(); // geting ids of all rows
var updateSortOrder = $.ajax({
url: baseUrl + 'mycontroller/updateimagesorder',
dataType: 'json',
traditional: true,
contentType: 'application/json',
data: JSON.stringify({ "sortOrder": sortOrder.split(',') }),
type: 'PUT'
});
updateSortOrder.done(function (result) {
closeModel('images-model');
});
and here is my server side method
[Route("updateimagesorder")]
public HttpResponseMessage PutImagesSortOrder([FromBody]string[] sortOrder)
{
// do stuff with parameters
}
Note : /mycontroller is route prefix here and baseUrl is my domain url
so , what the issue in my code ?
Try passing the value like this:
data: JSON.stringify(sortOrder.split(',')),
So that your request payload looks like a string array:
["foo", "bar"]
If you want to pass the value like that:
data: JSON.stringify({ "sortOrder": sortOrder.split(',') }),
then make sure that you have declared a view model:
public class MyViewModel
{
public string[] SortOrder { get; set; }
}
that your controller action will take as parameter:
[Route("updateimagesorder")]
public HttpResponseMessage PutImagesSortOrder(MyViewModel model)
{
// do stuff with parameters
}
i have the following code in c#. I'm using ASP.NET MVC 3.
public override void ExecuteResult(ControllerContext context)
{
// If ContentType is not expected to be application/json, then return XML
if ((context.HttpContext.Request.ContentType ?? String.Empty).Contains("application/json"))
{
new JsonResult { Data = this.Data }
.ExecuteResult(context);
}
else
{
using (MemoryStream stream = new MemoryStream(500))
{
using (var xmlWriter = XmlTextWriter.Create(
stream,
new XmlWriterSettings()
{
OmitXmlDeclaration = true,
Encoding = UTF8,
Indent = true
}))
{
new XmlSerializer(typeof(T), IncludedTypes)
.Serialize(xmlWriter, this.Data);
}
// NOTE: We need to cache XmlSerializer for specific type. Probably use the
// GenerateSerializer to generate compiled custom made serializer for specific
// types and then cache the reference
new ContentResult
{
ContentType = "text/xml",
Content = UTF8.GetString(stream.ToArray()),
ContentEncoding = UTF8
}
.ExecuteResult(context);
}
}
}
I'm trying to return a json or a xml result depending the request. The problem is that i get context.HttpContext.Request.ContentType = "" when i run it.
Is there a way to make the application know that the request is "application/json"?
I'm returning this result object in a controller method called GetGoogleMapsMarkers:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "http://localhost:1939/API/Google/GetGoogleMapsMarkers",
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
}
}
});
Help me please.
Thanks.
Unable to reproduce. Here's what I tried:
Result:
public class TestResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
var ct = context.HttpContext.Request.ContentType;
context.HttpContext.Response.Write(ct);
}
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Foo()
{
return new TestResult();
}
}
View:
<script type="text/javascript">
$.ajax({
url: '#Url.Action("foo")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
}
});
</script>
The AJAX call resulted in the correct request content type to be fetched.
i added
data: { },
to the ajax call and it worked.... it's weird but it made it work...