I have server mvc action with two parameters:
[HttpPost]
public ActionResult TestActionPost(string applicationId, Dictionary<string, int> myDictionary)
{
return null;
}
and ajax request:
<script type="text/javascript">
$(document).ready(function () {
$("#itemList").tableDnD({
onDrop: function (table, row) {
var items = $("table#itemList > tbody > tr[id]");
var dict = [];
var dataObject = [];
$.each(items, function (index, value) {
dict.push({
key: value.id,
value: index
});
});
dataObject.push("123");
dataObject.push(dict);
$.ajax({
url: "/Admin/Applications/TestActionPost/",
type: "POST",
contentType: "application/json; charset=utf-8",
data: { applicationId: JSON.stringify(dataObject[0]), myDictionary : JSON.stringify(dataObject[1]) },
traditional: true,
dataType: "json",
success: function (response) {
alert(response);
}
});
}
});
});
</script>
I try to send data to server action, but my action can't call. I get code HTTP 500.
Please,help me!
I think you're having issues with the way the dictionary is serializing which is causing an exception to be thrown when you call the action. This article explains how to create dictionary object which can then be sent by an ajax post.
Related
I need help, i can't send parameter from ViewData in javascript to Controller, maybe because in controller using JsonResult, but I haven't found the solution till now, is there any way to fix it ?
this my js :
var urlString2 = "#Url.Action("GetAttributeLabel", "MasterDataTemp")?modifierId=#ViewData["ModifierId"]";
$.ajax({
url: urlString2,
type: "GET",
dataType: "json",
contentType: 'application/json; charset=utf-8',
async: true,
processData: false,
cache: false,
success: function (data) {
$.each(data, function (i, item) {
dataAttributeLabel.push(item.AttributeName);
});
},
error: function (xhr) {
alert('error');
}
});
this is my controller :
public JsonResult GetAttributeLabel(Guid modifierId)
{
...........
}
The parameter always send empty guid, please help..
Please try like below
#{
string guid = ViewData["ModifierId"].ToString();
}
var urlString2 = "MasterDataTemp/GetAttributeLabel?modifierId="+"#guid";
$.ajax({
url: urlString2,
type: "GET",
dataType: "json",
success: function (data) {
$.each(data, function (i, item) {
dataAttributeLabel.push(item.AttributeName);
});
},
error: function (xhr) {
alert('error');
}
});
And at controller
public JsonResult GetAttributeLabel(string modifierId)
{
...........
}
Firstly, you have to avoid sending JSON data with jQuery Ajax GET request, if you do want to send JSON data, try with a POST request.
Secondly, you could generate the url in #Section like this:
#{
string val = ViewData["key"] != null ? ViewData["key"].ToString()
: "defaultval";
var routedic = new Dictionary<string, string>()
{
{ "key", val }
};
var url = Url.Action("Test", "Home", routedic);
}
And then send the request:
<script>
var urlstr="#(url)";
// check the uri in console
console.log(urlstr);
$.ajax({
url:urlstr,
type:"GET"
});
</script>
It works well now:
$('#SendEmail').click(function () {
var sel = $('input[type=checkbox]:checked').map(function (_, el) {
return $(el).val();
}).get();
alert(sel);
SetCompanyDetailsPopUp(sel);
})
I have multiple Check box in forloop and Iam getting the value at Onclick Function "SendEmail " and Also calling the Ajax method,The Ajax method "SetCompanyDetailsPopUp"is also working fine , but Parameter at server side is showing "null"
function SetCompanyDetailsPopUp(Email) {
debugger;
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "/CRMLogin/GeneratePass",
data: { "id": Value },
success: function (result) {
var data = '';
alert(result);
//alert(result);
//alert('sucessfully generated');
}
});
}
after Debugging Ajax Function The value in the "Email" parameter is
Array(2)
0:"1"
1:"2"
length:2
proto
:
Array(0)
serverside method
public ActionResult GeneratePass(string id)
{
string[] arr = id.Split(','); ; // Initialize.
// Loop over strings.
foreach (string s in arr)
{
forgotPassword(s);
}
return Json(arr, JsonRequestBehavior.AllowGet);
}
the issue from my point of view is that you don't have
[FromBody] attribute in your controller method which is needed in Post methods
please check the following link:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
So the Code should look like this:
[HttpPost]
public ActionResult GeneratePass([FromBody] string id)
{
string[] arr = id.Split(','); ; // Initialize.
// Loop over strings.
foreach (string s in arr)
{
forgotPassword(s);
}
return Json(arr, JsonRequestBehavior.AllowGet);
}
You need to add the" traditional: true "
"ajax option to post back an array to the collection
function SetCompanyDetailsPopUp(Email) {
debugger;
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "/CRMLogin/GeneratePass",
data: { "id": Email},
traditional: true, //Need to Add This
success: function (result) {
var data = '';
alert(result);
}
});
}
You do not give the attribute [httppost] to the method. But your ajax is post type. Here is the code sample that work as expected.
$(document).ready(function () {
function SetCompanyDetailsPopUp(Email) {
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "/CRMLogin/GeneratePass",
data: { "id": Email },
success: function (result) {
var data = '';
alert(result);
}
});
}
$('#SendEmail').click(function () {
var sel = $('input[type=checkbox]:checked').map(function (_, el) {
return $(el).val();
}).get();
SetCompanyDetailsPopUp(sel);
});
});
And then ActionMethod
[HttpPost]
public ActionResult GeneratePass(string[] Id)
{
return View();
}
Change your ajax code with this
function SetCompanyDetailsPopUp(Email) {
var Value = Email.value;
debugger;
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "/CRMLogin/GeneratePass",
data:'{ id:" '+ Value + ' "}', // May be i am right, Here is problem
success: function (result) {
var data = '';
alert(result);
//alert(result);
//alert('sucessfully generated');
}
});
}
i am writing a function in jquery which post the data to controller. currently it is posting form data to controller fine but when i post checkbox list with form data then it send always count 0 in controller here is my code.
function SubmitForm() {
var studentFormData = $("#frmStudent").serialize();
debugger;
var SubjectArraydata = new Array();
$(".chkSubject:checked").each(function () {
var row = {
"SubjectId": $(this).data("id")
};
SubjectArraydata.push(row);
});
$.ajax({
url: '#Url.Action("StudentForm", "Student")',
type: "POST",
dataType: "json",
data: studentFormData + JSON.stringify("&subjectData=" + SubjectArraydata),
async: true,
success: function (msg) {
},
error: function () {
}
});
}
Controller:
[HttpPost]
public ActionResult StudentForm(Student student, List<Subject> subjectData)
{
return Json(true);
}
any one tell me where is the problem in my code thank you.
Your cannot mix 'application/x-www-form-urlencoded' data (the contentType of your serialize() method) and 'application/json' data (the contentType of the JSON.stringify() method) like that.
Sinve you have confirmed that your only submitting one property of Subject, which is SubjectId and is typeof int, then you can append the SubjectId values to the serialized data.
var studentFormData = $("#frmStudent").serialize();
$(".chkSubject:checked").each(function () {
studentFormData += '&' + $.param({ SubjectIds: $(this).data("id") });
};
$.ajax({
url: '#Url.Action("StudentForm", "Student")',
type: "POST",
dataType: "json",
data: studentFormData,
success: function (msg) {
},
error: function () {
}
});
and change your controller method to
[HttpPost]
public ActionResult StudentForm(Student student, List<int> SubjectIds)
{
....
I think you use 'POST' method not correctly. You try to mix sending data as json and as url parameters.
data: studentFormData + JSON.stringify("&subjectData=" + SubjectArraydata),
what you send in data:
[
{...},
[{SubjectId: ''}, {SubjectId: ''}]
]
or:
{
1: {...},
subjectData: [{SubjectId: ''}, {SubjectId: ''}]
}
or some data sended as json, some in url?
Send all data in json, and dont serialize (jquery do it for you):
var data = [strudentFormData, subjectData];
$.ajax(..., data: data, ...);
The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}
In a AJAX request to the server in MVC, how can I pass a list of id's to the controller's action function?
I accept with or without use of Html helpers.
I know MVC's model binder has no problem when it comes to simple types like int, string and bool.
Is it something like I have to use and array instead in the action?
I don't care if I have to use an array or List and even if the strings I int or strings I can always convert them. I just need them on the server.
My List ids gives null at the moment.
Javascript:
var ids= [1,4,5];
// ajax request with ids..
MVC Action:
public ActionResult ShowComputerPackageBuffer(List<int> ids) // ids are null
{
// build model ect..
return PartialView(model);
}
EDIT: Added my AJAX request
$(document).ready(function () {
$('#spanComputerPackagesBuffer').on('click', function () {
var ids = $('#divComputerPackagesBuffer').data('buffer');
console.log('bufferIds: ' + bufferIds);
var data = {
ids: ids
};
var url = getUrlShowComputerPackageBuffer();
loadTable(url, "result", data);
});
});
// AJAX's
function loadTable(url, updateTargetId, data) {
var promise = $.ajax({
url: url,
dataType: "html",
data: data
})
.done(function (result) {
$('#' + updateTargetId).html(result);
})
.fail(function (jqXhr, textStatus, errorThrown) {
var errMsg = textStatus.toUpperCase() + ": " + errorThrown + '. Could not load HTML.';
alert(errMsg);
});
};
// URL's
function getUrlShowComputerPackageBuffer() {
return '#Url.Action("ShowComputerPackageBuffer", "Buffer")';
};
SOLUTIONS: // Thanks to #aherrick comment. I missed the good old "traditional"
$.ajax({
type: "POST",
url: '#Url.Action("ShowComputerPackageBuffer", "Buffer")',
dataType: "json",
traditional: true,
data: {
bufferIds: bufferIds
}
});
Use the traditional parameter and set it to true.
$.ajax({
type: "POST",
url: "/URL",
dataType: "json",
traditional: true,
data: {}
});
Try this one (I've checked it):
$(function () {
var ids = [1, 4, 5];
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("YourAction", "YourController")',
data: JSON.stringify( { ids: ids })
}).done(function () {
});
});
You have to make sure your contentType is application/json and your data is stringified.
public ActionResult SaveSomething(int[] requestData)
//or
public ActionResult SaveSomething(IEnumerable<int> requestData)
Using Action Result you cannot receive JSON object:
Using Controler:
[HttpPost]
[Route( "api/Controller/SaveSomething" )]
public object SaveTimeSheet( int[] requestData )
{
try
{
doSomethingWith( requestData );
return new
{
status = "Ok",
message = "Updated!"
};
}
catch( Exception ex )
{
return new
{
status = "Error",
message = ex.Message
};
}
}
java script:
var ids = [1,4,5];
var baseUrl: 'localhost/yourwebsite'
$.ajax({
url: baseUrl + '/api/Controller/SaveSomething',
type: 'POST',
data: JSON.stringify(ids),
dataType: 'json',
contentType: 'application/json',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
if (result != undefined) {
window.location.href = window.location.href;
}
},
async: false,
});