I need to implement functionality to upload files and save them relevant to the orderItemID (which I can get). The problem isn't getting the ID or using the ID to then save the files to the DB. The problem is passing this ID (which I can log out and see is there) into the controller to then be used, the parameter continues to come back NULL when it isn't.
I initially tried passing the orderItemID as a second parameter when uploading the document but that resulted in both the HttpPostedFileBase and the int of orderItemID coming back as NULL as soon as I entered the method.
I've tried passing the orderItemID through the ViewBag. feature but again it comes back as NULL
I'm now trying to make a second separate AJAX call which simply passes in an int (orderItemID) and then in the controller I can try other things but for now I'd just like to see the parameter not returning as NULL when I hit the breakpoint in the orderController.
View:
$('#confirmUploadDiagrambtn').on("click", function () {
var currentID = document.getElementsByName("orderitemid")[0].value;
var form = $("#file")[0].files[0];
var datastring = new FormData();
datastring.append('file', form);
//Order Item ID is logged out as the expected 12121
console.log("OrderID: " + currentID);
//Errors out saying parameter is NULL
setOrderItemID(currentID);
uploadDocument(datastring);
})
function setOrderItemID(cOrderItemID) {
$.ajax({
type: "POST",
url: '/Order/SetCurrentOrderItemID',
data: cOrderItemID,
contentType: false,
processData: false,
success: function (response) {
console.log('Item Success');
console.log(response);
},
error: function (status) {
console.log('Item Error');
console.log(status);
}
})
}
Controller:
[HttpPost]
public void SetCurrentOrderItemID(int orderItemID)
{
//I can try whatever later, just need the param to not be NULL
ViewBag.cOrderItemID = orderItemID;
}
Expected: orderItemID will equal 12121
Actual: NULL
Error: The parameters dictionary contains a null entry for parameter 'orderItemID' of non-nullable type 'System.Int32' for method 'Void SetCurrentOrderItemID(Int32)'
the "data" property in the AJAX parameters should look like:
data: "cOrderItemID=" + cOrderItemID
EDIT:
remove this line:
contentType: false,
use this format:
data : {OrderItemID : cOrderItemID}
By default int parameters are assumed to come from the query string, you could either change the url to:
function setOrderItemID(cOrderItemID) {
$.ajax({
type: "POST",
url: '/Order/SetCurrentOrderItemID?orderItemID=' + cOrderItemID,
contentType: false,
processData: false,
success: function (response) {
console.log('Item Success');
console.log(response);
},
error: function (status) {
console.log('Item Error');
console.log(status);
}
})
}
Or else you could mark the parameter with the [FromBody] attribute:
[HttpPost]
public void SetCurrentOrderItemID([FromBody] int orderItemID)
{
//I can try whatever later, just need the param to not be NULL
ViewBag.cOrderItemID = orderItemID;
}
and then update your data parameter to:
data: JSON.stringify({orderItemId: cOrderItemID}),
Related
I have an AJAX function in my javascript to call my controller method. When I run the AJAX function (on a button click) it doesn't hit my break points in my method. It all runs both the success: and error:. What do I need to change to make it actually send the value from $CSV.text to my controller method?
JAVASCRIPT:
// Convert JSON to CSV & Display CSV
$CSV.text(ConvertToCSV(JSON.stringify(data)));
$.ajax({
url: '#Url.Action("EditFence", "Configuration")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { value : $CSV.text() },
success: function(response){
alert(response.responseText);
},
error: function(response){
alert(response.responseText);
}
});
CONTROLLER:
[HttpPost]
public ActionResult EditFence(string value)
{
try
{
WriteNewFenceFile(value);
Response.StatusCode = (int)HttpStatusCode.OK;
var obj = new
{
success = true,
responseText = "Zones have been saved."
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
var obj = new
{
success = false,
responseText = "Zone save encountered a problem."
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
}
RESULT
You should change the data you POST to your controller and the Action you POST to:
data: { value = $CSV.text() }
url: '#Url.Action("EditFence", "Configuration")'
The $CSV is possible a jquery Object related to an html element. You need to read it's text property and pass this as data, instead of the jQuery object.
Doing the above changes you would achieve to make the correct POST. However, there is another issue, regarding your Controller. You Controller does not respond to the AJAX call after doing his work but issues a redirection.
Update
it would be helpful for you to tell me how the ActionResult should
look, in terms of a return that doesn't leave the current view but
rather just passes back that it was successful.
The Action to which you POST should be refactored like below. As you see we use a try/catch, in order to capture any exception. If not any exception is thrown, we assume that everything went ok. Otherwise, something wrong happened. In the happy case we return a response with a successful message, while in the bad case we return a response with a failure message.
[HttpPost]
public ActionResult EditFence(string value)
{
try
{
WriteNewFenceFile(value);
Response.StatusCode = (int)HttpStatusCode.OK;
var obj = new
{
success = true,
responseText= "Zones have been saved."
};
return Json(obj, JsonRequestBehavior.AllowGet));
}
catch(Exception ex)
{
// log the Exception...
var obj = new
{
success = false,
responseText= "Zone save encountered a problem."
};
return Json(obj, JsonRequestBehavior.AllowGet));
}
}
Doing this refactor, you can utilize it in the client as below:
$CSV.text(ConvertToCSV(JSON.stringify(data)));
$.ajax({
url: '#Url.Action("EditFence", "Configuration")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { value = JSON.stringify($CSV.text()) },
success: function(response){
alert(response.responseText);
},
error: function(response){
alert(response.responseText);
}
});
If your javascript is actually in a JS file and not a CSHTML file, then this will be emitted as a string literal:
#Url.Action("EditFile", "Configuration")
Html Helpers don't work in JS files... so you'll need to point to an actual url, like '/configuration/editfile'
Also, it looks like you're posting to a method called EditFile, but the name of your method in the controller code snippet is EditFence, so that will obviously be an issue too.
you dont need to add contentType the default application/x-www-form-urlencoded will work because it looks like you have a large csv string. So your code should be like this example
$(document).ready(function() {
// Create Object
var items = [
{ name: "Item 1", color: "Green", size: "X-Large" },
{ name: "Item 2", color: "Green", size: "X-Large" },
{ name: "Item 3", color: "Green", size: "X-Large" }
];
// Convert Object to JSON
var $CSV = $('#csv');
$CSV.text(ConvertToCSV(JSON.stringify(items)));
$.ajax({
url: '#Url.Action("EditFence", "Configuration")',
type: "POST",
dataType: "json",
data: {value:$CSV.text()},
success: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
Your problem is on these lines:
success: alert("Zones have been saved."),
error: alert("Zone save encountered a problem.")
This effectively running both functions immediately and sets the return values of these functions to the success and error properties. Try using an anonymous callback function.
success: function() {
alert("Zones have been saved.");
},
error: function() {
alert("Zone save encountered a problem.")
}
I am trying to call MVC Controller from jquery but not able to place the call. Is there any problem in below code
Please figure out that if any problem and also I am not getting any error.
url="http://localhost:49917/Account/SaveAddress"
this.SaveAddress = function (url, addressData)
{
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: JSON.stringify(addressData),
contentType: 'application/json; charset=utf-8',
success: function (responseDetail) {
},
error:function(e)
{
},
});
return 0;
};
public async Task<ActionResult> SaveAddress(AddressListViewModel addressListVM)
{
bool response;
string message;
if (addressListVM.ID <= 0)
{
response = await Task.Run(() => AccountManager.Instance().AddAddress(addressListVM));
message = response ? "New address added successfully." : "Failed to add new address.";
}
else
{
response = await Task.Run(() => AccountManager.Instance().UpdateAddress(addressListVM));
message = response ? "Selected address updated successfully." : "Failed to update selected address.";
}
ModelState.Clear();
return Json(new { responsestatus = response, message = message }, JsonRequestBehavior.AllowGet);
//return PartialView("_AddressDetail", BuildAddressListEntity(
// UserManager.FindById(User.Identity.GetUserId()), response, message, addressListVM.ID, true));
}
Yes, you are missing a closing bracket at the end of the this.saveaddress function
this.SaveAddress = function (url, addressData)
{
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: JSON.stringify(addressData),
contentType: 'application/json; charset=utf-8',
success: function (responseDetail) {
},
error:function(e)
{
},
});
after all of that .. you need one more closing bracket:
}
;)
What does the console display? If you are using Chrome then right-click, choose Inspect, and find the Console tab. If you are calling the AJAX function correctly then something must be displayed in this Console tab which will probably lead you in the right direction better than I could with the information I have.
Put a breakpoint in your success and error functions. If it hits the error function then the issue is either that the controller action was not found or that the data is not valid json (either the post data or return data). You should add the errorThrown parameter to the error function so you can easily see what the issue is. You also do not need to stringify the data if it is already valid json, but if it is a string representing json data, you will need to use json.parse (sorry for the incorrect case).
I'm trying to pass a string parameter to a javascript function from the server side which will be posted to an AJAX method. The html is dynamically generated at the server side and I'm calling the javascript function using onclick property. The problem is that it works for a numeric value but I get an internal server error when I pass in a string value.
here's my server side code:
str.Append("<span class=\"button-accept\"><a class=\"btn btn-primary btn-sm\" onclick=\"Request('"+from.ToString()+"')\" href=\"#\"><i class=\"fa fa-check\"></i></a></span>");
Here's my javascript method:
function Request(param) {
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/myaccount/notifications/Default.aspx/Accept") %>',
data: "{'param' : "+param+"}",
contentType: "application/json",
success: function (msg) {
msg = msg.hasOwnProperty("d") ? msg.d : msg;
alert(msg);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
and here's the method that will be called by AJAX:
[WebMethod]
public static string Accept(string param)
{
return param;
}
What's the right way to do this?
The JSON you are passing to the web method is implying that it is an numeric value, add quotes surrounding the param value:
Old
data: "{'param' : "+param+"}",
New
data: "{'param' : '"+param+"'}",
Alternatively ...
If a string is always passed to your Request method, it will be correctly handled using JSON.stringify
data: JSON.stringify({ 'param' : param }),
How can I pass parameter to .NET web method with fancytree
Public Shared Function ReadNodes(parentId As String) As String
I am trying to send it like this, but it always gets sent as a querystring parameter.
$("#tree").fancytree( {
source: {
url: "Default.aspx/ReadNodes",
data: {parentId: "-1"},
cache: false
}
} )
Can I somehow pass the value to a method as a parameter?
This doesnt work, I keep getting a loading wheel and then a failure. No javascript errors in console.
I have also tried the server method without a parameter, and I get the same behavior. So perhaps I am doing something else wrong.
Your web method must return an array like:
[WebMethod]
public static IEnumerable ReadNodes(int parentId)
{
return new[] {
new { title = string.Format("1. Child of '{0}'", parentId) },
new { title = string.Format("2. Child of '{0}'", parentId) }
// ...
};
}
And then you call the web method like this
$('#tree').fancytree({
source: {
type: 'POST',
url: 'Default.aspx/ReadNodes',
data: '{ parentId: -1 }',
contentType: 'application/json;',
dataType: 'json'
}
});
I am posting a JSON string to asp.net MVC as follows.
AJAX call
$.ajax({
type: "POST",
url: "#(storeLocation)IDR/OpcInsertCustomerProfile/",
data: JSON.stringify(currSelection),
contentType: "application/json",
success: function(data) {
alert('success : ' + JSON.stringify(data));
},
error: function(data) {
alert('Error : ' + JSON.stringify(data));
}
}
);
In the controller:
[HttpPost]
[ActionName("OpcInsertCustomerProfile")]
public JsonResult OpcInsertCustomerProfile(string currSelectionData)
{
try
{
JavaScriptSerializer ser = new JavaScriptSerializer();
var res = ser.Serialize(currSelectionData);
return Json(currSelectionData, JsonRequestBehavior.AllowGet);
}
catch (Exception exc)
{
return Json(new { error = 1, message = exc.Message });
}
}
Debugger indicates the action gets called successfully, however the incoming string parameter being received is always null. Firebug 'post' shows outgoing parameter is proper json object. I am expecting to see the JSON string as incoming parameter. Please note that I don't want to de-serialise it into proper object. All I want to do is store the string in JSON format 'as-it-is' in a database. Later on it needs be retrieved ans passed to Javascript as it is.
Try this :
$.ajax({
type: "POST",
url: "#(storeLocation)IDR/OpcInsertCustomerProfile/",
data: { "currSelectionData" : "'" + JSON.stringify(currSelection) + "'" },
contentType: "application/json",
success: function(data) {
alert('success : ' + JSON.stringify(data));
},
error: function(data) {
alert('Error : ' + JSON.stringify(data));
}
}
);
One way is to allow the action to receive the parameter as POST data instead of JSON "Stringified" data. To do that, post the data without JSON.Stringify. Hopefully this is what you need.
If not you might want to try creating an object just to receive this simple data.
Look at your action method: is it correct that method accepts string with serialized JSON, than serialized that string as JSON again and then dismiss the result and serializes and returns the same string again?
If you send request with application/json type ASP.NET MVC tries to deserialize received string and bind it to action parameters: in your case it tries to find property currSelectionData inside your JSON object. Is that property exists? Maybe you expect whole string is received as currSelectionData parameter? Then you need to use FormCollection or Request.Form instead because default model binder does not support this.
Actually i fill my state dropdown in selection of country with json i do like this
in my controller i have action it's return my data in json format like this it's below
public JsonResult State(int countryId)
{
var stateList = CityRepository.GetList(countryId);
return Json(stateList, JsonRequestBehavior.AllowGet);
}
in my view
<script type="text/javascript">
function cascadingdropdown() {
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
var countryID = $('#countryID').val();
$.ajax({
url: "/City/State",
dataType: 'json',
data: { countryId: countryID },
success: function (data) {
$("#stateID").empty();
$("#stateID").append("<option value='0'>--Select State--</option>");
$.each(data, function (index, optiondata) {
alert(optiondata.StateName);
$("#stateID").append("<option value='" + optiondata.ID + "'>" + optiondata.StateName + "</option>");
});
},
error: function () {
alert('Faild To Retrieve states.');
}
});
}
</script>
i think this will help you...
When sending json through Ajax, I think this is the right approach for the data property in Ajax:
data: "{'parameterNameInAction':'" + JSON.stringify(jsonData) + "'}"