I am trying to sent a byte[] in a postback action, but failed to get it.
Code snippets:
$.ajax({
url: proxy.Model.RequestParamUrl,
type: "Post",
async: false,
data: proxy.requestArgs,
dataType: 'json',
success: function (Jsondata) {
proxy.allowPost = false;
proxy.postSucceed = true;
//hidden code
return true;
}
});
While debugging, I can see byte[] in proxy.requestArgs.
But in the controller, I get null in this action result.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(byte[] param)
{
//I get null in this param.
}
Anything I am missing out?
Any Solution
You're passing data to the controller action and that action is expecting a post item named param. So in your JS, make your ajax call look like this (note the change to data):
$.ajax({
url: proxy.Model.RequestParamUrl,
type: "Post",
async: false,
data: { param: proxy.requestArgs },
dataType: 'json',
success: function (Jsondata) {
proxy.allowPost = false;
proxy.postSucceed = true;
//hidden code
return true;
}
});
Have you tried this?
Basically, accept the data as string in you action and inside it convert it into byte[]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string param)
{
var bytes = System.Text.Encoding.UTF8.GetBytes(param);
}
Related
I'm trying to get some string from my Controller and use it in the View.
The ActionResult works like this:
public ActionResult GetSymbols()
{
string result = "SVG-String";
return Content(result);
}
This result is will be a svg-formatted string and should be shown in my svg-drawing, at the end.
I tried to call this controller-Action, using JavaScript and I could reach the Controller but how could I use the String? I couldn't see any result, so what is the rigth way to get the returned string into a variable?
The last try was like this:
$(document).ready(function () {
$.ajax({
url: "/Symbols/GetSymbols/",
method: "GET",
async: false,
data: "",
dataType: "string",
success: function (data) { alert(data); }
});
});
How about this one,
Change your Controller return type to Json
[HttpGet]
public JsonResult GetSymbols()
{
string result = "SVG-String";
return Json(result, JsonRequestBehavior.AllowGet);
}
And your javascript be like,
$(document).ready(function () {
$.ajax({
method: "GET",
url: "/Symbols/GetSymbols/",
async: false,
dataType: "json",
success: function (data) {
alert(data);
},
error: function (response) {
console.log(response);
}
});
});
I want to pass the variable from view to controller I am using ajax call to achieve it i am getting the error below. I don't know what i am missing here.
WARN 41440 --- [nio-8080-exec-9] o.s.web.servlet.PageNotFound : Request method 'POST' not supported
This is my code
document.getElementById('btntest').onclick = function(){
var selchbox = getSelectedChbox(this.form); // gets the array returned by getSelectedChbox()
myvalue = JSON.stringify(selchbox);
//document.write("check check"+selchbox);
$.ajax({
type: "POST",
url: "UserController/delete",
contentType: "application/json; charset=utf-8",
data: {key:myvalue},
cache: false,
success: function (data) {
alert("Are you sure?");
},
error: function (args) {
alert("Error on ajax post");
}
});
alert(selchbox);
}
My controller method looks like below
#RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(#RequestBody String key) {
System.out.println("My Array value"+key.toString());
return key;
}
What i am missing here? Any Help
Finally i could able to pass the values from my view to controller I am posting the code.
This is my js code
document.getElementById('btntest').onclick = function(){
var selchbox = getSelectedChbox(this.form); // gets the array returned by getSelectedChbox()
var myvalue = JSON.stringify(selchbox);
//document.write("check check"+selchbox);
$.ajax({
type: "POST",
url: "/delete",
dataType : "JSON",
contentType:"application/json; charset=utf-8",
data: JSON.stringify(selchbox),
cache: false,
success: function (data) {
alert("Are you sure?");
},
error: function (args) {
alert("Error on ajax post");
}
});
alert(selchbox);
}
And my controller code
#RequestMapping(value = "/delete", method = RequestMethod.POST)
public String delete(#RequestBody String value){
System.out.println("My Array value"+value.toString());
return value;
}
First, if you want to delete, why not use the verb delete http?
I think you are not using the correct parameter: RequestParam is used to map your sORGID parameter to the URL (a parameter you did not use on the client side, you must use it or delete it).
If you want to map Json, you must use #RequestBody.
I hope it helps
At leaset two problems
url: "UserController/delete" in your ajax won't match "/delete/{sORGID}" in your controller.
data: {key:myvalue} in your ajax, the property name is key, in your controller it's myvalue[], this should also be the same.
Data doesn't passing to controller, always null
My script in view:
function deleteRecords() {
var selected = [];
$('#myTable input:checked').each(function () {
selected.push($(this).attr('id'));
});
$.ajax({
url: '/Home/DeleteRecords',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { "json": JSON.stringify(selected) },
error: function () {
alert("Error!");
}
});
}
My home controller method:
[HttpPost]
public IActionResult DeleteRecords(string AllId)
{
return null;
}
send ajax request data like below,
$.ajax({
url: '/Home/DeleteRecords',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(selected),
error: function () {
alert("Error!");
}
});
and receive the data in action like
[HttpPost]
public IActionResult DeleteRecords(string[] AllId)
{
return null;
}
It need to pass the action. Hope it helps to you.
with the code in your question, try below to get the json
System.Web.Context.Current.Request.Form["json"]
if you want some more graceful stuff, you need to put FromBody attribute in your parameter signature
DeleteResults([FromBody] string json)
Name your property in the Post the same as your method so that the automatic binding picks it up. - Turns out this doesn't matter for single object.
The data Object you were creating was not parse-able by .net, use JSON.stringify directly for the data payload.
Note: The change in Home controller since you are passing an array of string.
function deleteRecords() {
var selected = [];
$('#myTable input:checked').each(function () {
selected.push($(this).attr('id'));
});
$.ajax({
url: '/Home/DeleteRecords',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(selected),
error: function () {
alert("Error!");
}
});
}
For your home controller method:
[HttpPost]
public IActionResult DeleteRecords(string[] AllId)
{
return null;
}
I try to send values from my view to my controller.
The method in my controller is called but the value(s) still remain NULL.
Here is the Javascript part:
GUIRequests.prototype.SetNewItemDeliveryValues = function () {
var modelNumberID = this.GetValue('#ModelNumberID');
this.Request.GetPreOrderIDForModelNumberID(modelNumberID); //InventValueRequest
this.Request.GetShortfallAndOverdeliveryInNewItemDelivery(modelNumberID);
}
InventValueRequest.prototype.GetPreOrderIDForModelNumberID = function (_modelNumberID) {
this.CallAjax("/NewItemDelivery/GetPreOrderIDForModelNumberID", _modelNumberID, CallbackMethods.SetPreOrderID);
}
//Private
InventValueRequest.prototype.CallAjax = function (_url, _data, _successFunctionPointer) {
$.ajax({
type: 'POST',
url: _url,
contentType: 'application/json',
data: JSON.stringify(_data),
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
}
Asp.Net MVC5 (C#) part
[HttpPost]
public ActionResult GetPreOrderIDForModelNumberID(string _modelnumberID)
{
String preOrderID = "";
if (_modelnumberID == null)
{
preOrderID = "No value received";
}
else
{
//Do something
}
return Json(preOrderID);
}
What could be the problem with my code ? why don't I receive any values in my C# part ? It seems that the values get send correctly, at least the payload contains the values I would expect.
_data should have the property _modelnumberID like following.
_data = {'_modelnumberID': '1'}
try below code :
$.ajax({
type: 'POST',
dataType: 'text',
url: _url,
contentType: 'application/json',
data: "_modelnumberID=" + _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
The Ideal solution would be to use a view model.
public class Create
{
public string _modelnumberID{get;set;}
}
And your HttpPost action would be accepting an object of this
[HttpPost]
public ActionResult View(Create model)
{
// do something and return something
}
and ajax will be
$('.submit').click(function () {
var myData = {
_modelnumberID: _data
}
$.ajax({
url: '/Controller/Action',
type: 'POST',
data: myData,
processData: false
}).done(function () {
}).fail(function () {
});
});
$.ajax({
type: 'POST',
url: _url+"?_modelnumberID="+ _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
Try this.
I'm trying to get started with ASP.NET MVC Ajax calls.
Controller:
public class AjaxTestController : Controller
{
//
// GET: /AjaxTest/
public ActionResult Index()
{
return View();
}
public ActionResult FirstAjax()
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
}
View:
<head runat="server">
<title>FirstAjax</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var serviceURL = '/AjaxTest/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: param = "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
</script>
</head>
I just need to print an alert with the controller method returning data. Above code just print "chamara" on my view. An alert is not firing.
UPDATE
I modified my controller as below and it start working. I don't have an clear idea why it's working now. Some one please explain. The parameter "a" does not related i added it because i can not add two methods with same method name and parameters.I think this might not be the solution but its working
public class AjaxTestController : Controller
{
//
// GET: /AjaxTest/
[HttpGet]
public ActionResult FirstAjax()
{
return View();
}
[HttpPost]
public ActionResult FirstAjax(string a)
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
}
Remove the data attribute as you are not POSTING anything to the server (Your controller does not expect any parameters).
And in your AJAX Method you can use Razor and use #Url.Action rather than a static string:
$.ajax({
url: '#Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
From your update:
$.ajax({
type: "POST",
url: '#Url.Action("FirstAjax", "AjaxTest")',
contentType: "application/json; charset=utf-8",
data: { a: "testing" },
dataType: "json",
success: function() { alert('Success'); },
error: errorFunc
});
After the update you have done,
its first calling the FirstAjax action with default HttpGet request
and renders the blank Html view . (Earlier you were not having it)
later on loading of DOM elements of that view your Ajax call get fired and displays alert.
Earlier you were only returning JSON to browser without rendering any HTML. Now it has a HTML view rendered where it can get your JSON Data.
You can't directly render JSON its plain data not HTML.
Use a Razor to dynamically change your URL by calling your action like this:
$.ajax({
type: "POST",
url: '#Url.Action("ActionName", "ControllerName")',
contentType: "application/json; charset=utf-8",
data: { data: "yourdata" },
dataType: "json",
success: function(recData) { alert('Success'); },
error: function() { alert('A error'); }
});
If you just need to hit C# Method on in your Ajax Call you just need to pass two matter type and url if your request is get then you just need to specify the url only. please follow the code below it's working fine.
C# Code:
[HttpGet]
public ActionResult FirstAjax()
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
Java Script Code if Get Request
$.ajax({
url: 'home/FirstAjax',
success: function(responce){ alert(responce.data)},
error: function(responce){ alert(responce.data)}
});
Java Script Code if Post Request and also [HttpGet] to [HttpPost]
$.ajax({
url: 'home/FirstAjax',
type:'POST',
success: function(responce){ alert(responce)},
error: function(responce){ alert(responce)}
});
Note: If you FirstAjax in same controller in which your View Controller then no need for Controller name in url. like url: 'FirstAjax',
First thing there is no need of having two different versions of jquery libraries in one page,either "1.9.1" or "2.0.0" is sufficient to make ajax calls work..
Here is your controller code:
public ActionResult Index()
{
return View();
}
public ActionResult FirstAjax(string a)
{
return Json("chamara", JsonRequestBehavior.AllowGet);
}
This is how your view should look like:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var a = "Test";
$.ajax({
url: "../../Home/FirstAjax",
type: "GET",
data: { a : a },
success: function (response) {
alert(response);
},
error: function (response) {
alert(response);
}
});
});
</script>
It's for your UPDATE question.
Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:
UPDATE:
[HttpGet]
public ActionResult FirstAjax()
{
Some Code--Some Code---Some Code
return View();
}
[HttpPost]
[ActionName("FirstAjax")]
public ActionResult FirstAjaxPost()
{
Some Code--Some Code---Some Code
return View();
}
And please refer this link for further reference of how a method becomes an action. Very good reference though.
View;
$.ajax({
type: 'GET',
cache: false,
url: '/Login/Method',
dataType: 'json',
data: { },
error: function () {
},
success: function (result) {
alert("success")
}
});
Controller Method;
public JsonResult Method()
{
return Json(new JsonResult()
{
Data = "Result"
}, JsonRequestBehavior.AllowGet);
}
instead of url: serviceURL,
use
url: '<%= serviceURL%>',
and are you passing 2 parameters to successFunc?
function successFunc(data)
{
alert(data);
}
Add "JsonValueProviderFactory" in global.asax :
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}