C# MVC pass parameters from View to Controller using dotnetfiddle - javascript

I am learning C# MVC using dotnetfiddle web to write code.
I have created a new project with the default code of dotnetfiddle for MVC type, but I want to display the question in the alert instead of the answer.
I want to know how to pass parameters to the controller from the view.
This is the ajax method:
$.ajax({
url: '#Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
data: JSON.stringify({Answer: '', Question: $('#Question').val()}),
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resp) {
openAlert(resp.result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + errorThrown);
}
});
And this is the controller method:
[HttpPost]
public JsonResult GetAnswer(string question)
{
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(new { result = question});
}
You can check and test the code here: dotnetfiddle (Edit: it will be a good answer if it works here)

These code changes will work for you. If you wanna verify check the fiddle. DotNetFiddle
Client side Changes
$.ajax({
url: '#Url.RouteUrl(new{ action="GetAnswer", controller="Home"})',
data: {"Answer": '', "Question": $('#Question').val()},
type: 'POST',
success: function(resp) {
openAlert(resp.Question);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + errorThrown);
}
});
Server Side Changes
[HttpPost]
public JsonResult GetAnswer(SampleViewModel model)
{
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(model);
}

This is the method I used to pass parameters to controller
First, assign the parameter you want to pass to a variable with the value from the
input id as stated in your dotnetfiddle
var questionParam = $("#Question").val();
Then for passing it to AJAX, I think your method is already correct, this is how I do it
$.ajax({
url: '/Home/GetAnswer?question=' + questionParam ,
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resp) {
openAlert(resp.result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + errorThrown);
}
});
This method works for me in my project, if the value is a string I think you don't need to stringify the value.
I'm still a beginner as well so maybe my method is wrong or not the best way to do it, I hope it helps you.

You are getting the value of the question in the action because your action has got a single parameter string question in there.
What you need to do is:
Send a json object from the view
In the action user a model with two properties (Answer and Question) to get the value sent by the view
Then in the action you decide what data you need to send to view
View:
Send JSON object to action:
JSON.stringify({Answer: '', Question: $('#Question').val()})
When you get the data returned from controller:
openAlert(resp.Answer);
Controller:
public JsonResult GetAnswer(MyQA model)
{
// model.Answer
// model.Question
// Your business logic goes here
return Json(new { result = model});
}
Here is the MyQA class:
public class MyQA
{
public string Answer { get; set; }
public string Question{ get; set; }
}

dotnetfiddle had a problem with this line: contentType: "application/json; charset=utf-8",
change script to :
$('.submit').click(function() {
if ($('form').valid()) {
$.ajax({
url: '#Url.Action("GetAnswer", "Home")',
data: {
Answer: '',
Question: $('#Question').val()
},
type: 'POST',
dataType: 'json',
success: function(resp) {
openAlert('Answer :' + resp.Answer + ' -----Question : ' + resp.Question);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
openAlert("ERROR: " + textStatus);
}
});
} else {
closeAlert();
}
});
change action GetAnswer to :
[HttpPost]
public JsonResult GetAnswer(string Answer,string Question)
{
int index = _rnd.Next(_db.Count);
var answer = _db[index];
return Json(new {Answer = answer,Question = Question});
}

Related

AJAX post data is null when it reaches the ASP.NET Core 2.1.1 controller

I have a problem posting a value from java-script in my razor page to a controller. - the value received is always null.
I have seen similar questions being asked, but have not been able to find the right solution to the problem.
I get to a break point in the controller, (so the routing is okay) but the parameter value passed is always null, and not being the sharpest in java-script, I would like some tips from you folks.
I basically have the java-script below:
var clickButton = function (buttonId) {
$.ajax({
type: "POST",
async: false,
cache: false,
crossDomain: false,
contentType: "application/json; charset=utf-8",
url: "v1/buttons",
dataType: "json",
data: '{ buttonId:'+JSON.stringify( "buttonId" ) + '}',
success: function (result) {
//console.log("clickButton OK => " + result);
}, //success: function (result) {
timeout: 500 // 0.5 sec.
}); //$.ajax({
}//var clickButton = function(buttonNo) {
and the C# controller code below too:
[Route( "v1/[controller]" )]
public class ButtonsController : Controller
{
...
[HttpPost]
public IActionResult OnButtonClicked( string buttonId )
{
// buttonId = null !!!
...
I have a similar problem getting a boolean value across to another controller.
where the bool is always false.. i.e. the default value.
I am wondering if it is a security issue, with not allowing the post to contain data, when the user is unauthorized...
The problem was in the JSON, and I got the value through with this minor change, but it was hiding well.
var clickButton = function (buttonNo) {
console.log("clicked: " + buttonNo);
$.ajax({
type: "POST",
url: "v1/buttons/",
dataType: "json",
data: { "buttonId": buttonNo }, // < === this is where the problem was !!
success: function (result) {
}, //success: function (result) {
}); //$.ajax({
}//var clickButton = function(buttonNo) {
I've changed the controller to receive a string to id the button.
And it now looks like this:
[Route( "v1/[controller]" )]
public class ButtonsController : Controller
{
...
[HttpPost]
public IActionResult PostButtonClick( string buttonId ) {
// buttonId now has a value !!!
}
}

Error while calling Webapi in my asp.net project

This is my api code that return successfull json data while using get method
public Question[] Get() {
getQuestion obj = new AllDataAccess.getQuestion();
return obj.questionList().ToArray();
}
This is my post method data that accept the value and save in database
public void Post([FromBody] string question) {
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
This is the method that call my api
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values',
data: "{'question':'" + $("#submit").value + "'}",
dataType: 'json',
async: false,
success: function(data, status) {
console.log(status);
},
error: function(err) {
console.log(err);
}
});
Now the problem is when i post the data with one textbox value its give me a message in console that "nocontent" and record save in data base with null value
It seems that your ajax url is wrong. You should specify the action name (post). Also, use JSON.stringify to retrieve proper json from javascript object.
var postData = { question:$("#submit").val() };
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values/post',
data: JSON.stringify(postData),
dataType: 'json',
success: function (data,status) {
console.log(status);
},
error: function (err) {
console.log(err);
}
});
In the server side, you should create a model class for Post method;
public class PostInput
{
public string Question { get; set; }
}
And then Post method looks like;
[HttpPost]
public void Post([FromBody]PostInput input)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
If you want to use FromBody, you can do so.
JavaScript
$.ajax({
type: "POST",
//default content-type, could be omitted
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: 'http://localhost:53893/api/values/post',
data: {'': $("#submit").val()}
});
API action
[HttpPost]
public void Post([FromBody]string question)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
You had these issues.
Wrong content-type for your ajax call.
Data was not posted correctly.
val() should be used instead of .value.
API action should be decorated with [HttpPost].

cannot send json or text to C# bhind-code using AJAX

I have an AJAX code where I am trying to send some data to a method within C# code-behind
I've tried to send them either using text data type and json data type, but neither of them are working with me.
when I use json type, it returns me the following error:
Internal Server Error
and when using text me
thod, there is no error appear and the code comes through the success function, but the actually the data is never sent to the method of the code-behind class
this is the ajax code using json type:
function searchClicked(sCriterion) {
$.ajax({
type: "POST",
url: "TokenRegistration.aspx/GetSearchCritetrion",
data: "{creiterion : " + sCriterion + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
And this is the ajax code using the text format:
function searchClicked(sCriterion) {
$.ajax({
type: "POST",
url: "TokenRegistration.aspx/GetSearchCritetrion",
data: sCriterion,
contentType: "application/text; charset=utf-8",
dataType: "text",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
Also here is the my code-behind method that the data should be sent to:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetSearchCritetrion(object selectedItem)
{
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(selectedItem.ToString());
}
I've used the exact same ajax code in another project and it works perfectly, but here i'm not getting where the error is, so any suggestions please?
see if this works
instead of sending object try to pass as string
data: JSON.stringify({selectedItem : sCriterion }),
code behind
public void GetSearchCritetrion(string selectedItem)
Here is a really simple example that posts JSON to a controller method, which converts this into an object and then returns a response.
HTML:
<button id="go" class="btn">Go</button>
JS:
var obj = { foo: 123, bar: "abc " };
$('#go').click(function () {
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Test/TestJson',
data: JSON.stringify(obj),
success: function (response) {
alert(response.result)
},
failure: function (response) {
alert('fail');
}
});
});
Controller:
public class TestController : Controller
{
[OutputCache(Location = OutputCacheLocation.None)]
public JsonResult TestJson(TestClass tc)
{
return Json(new { result = "foo=" + tc.foo + " bar=" + tc.bar }, JsonRequestBehavior.AllowGet);
}
public class TestClass
{
public int foo { get; set; }
public string bar { get; set; }
}
}
I think this help you.
class Item
{
public int id { get; set; }
}
[WebMethod]
public static void GetSearchCritetrion(Item selectedItem)
{
//ToDo: selectedItem.id
}

JavaScript POST falls when connect to MVC controller

I'm new in MVC and trying to create a site for training.
I need to call a POST method in my controller through JavaScript.
This is my JavaScript method:
function ActivateAddStarAndRoleWithCategories(sender, args) {
var discID = $('#DiscID').val();
var starID = $('#StarID').val();
var desc = $("#Description").val();
var strID = "";
$(':checkbox').each(function () {
strID += this.checked ? this.id + "," : "";
});
strID = strID.substr(0, strID.length - 1);
$.ajax({
type: "POST",
url: 'CreateCategoriesID',
contentType: "application/json; charset=utf-8",
data: {
discID: discID,
starID: starID,
description: desc,
catID: strID
},
dataType: "json",
success: function () { alert("success!"); },
error: function () { alert("Fail!"); }
});
}
And this is my method in the controller:
[HttpPost]
public ActionResult CreateCategoriesID(string discID, string starID, string description, string catID)
{
entities.AddStarAndRoleAndCategories(int.Parse(starID), description, int.Parse(discID), catID);
return Json("OK", JsonRequestBehavior.AllowGet);
}
The view that activates the JavaScript function is already connected to the controller.
I always get error 500 - the server responded with a status of 500.
What am I doing wrong?
Thank you in advance!
I would go with the examples from the jQuery docs.
Did you try something like...?
$.ajax({
method: "POST",
url: "CreateCategoriesID", // Insert your full URL here, that COULD be the problem too
// This contentType is the default, so we can just ignore it
//contentType: "application/x-www-form-urlencoded; charset=UTF-8",
// I would also ignore the dataType unless your backend explicitly sends a JSON response header
//dataType: "json",
data: {
discID: discID,
starID: starID,
description: desc,
catID: strID
}
}).done(function(msg) {
alert('Success with message: ' + msg);
}).fail(function(jqXHR, textStatus) {
alert('Failed with status: ' + textStatus);
});

asp.net ashx handler: can't receive response

Hello everyone and thanks for your time.
Here is my javascript:
$('.sender').click(function (e) {
$.ajax({
type: "POST",
url: "fHandler.ashx",
data: { firstName: 'stack', lastName: 'overflow' },
// DO NOT SET CONTENT TYPE to json
// contentType: "application/json; charset=utf-8",
// DataType needs to stay, otherwise the response object
// will be treated as a single string
dataType: "json",
success: function (response) {
alert('success');
},
error: function (response) {
alert('error: ' + response);
console.log('err: '+response);
}
});
});
And here is the code in my .ashx handler:
public void ProcessRequest(HttpContext context)
{
context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//to fix the allow origin problem
context.Response.ContentType = "text/plain";
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
context.Response.Write(json);
}
public bool IsReusable
{
get
{
return false;
}
}
While the click event is working, my Ajaxrequest doesn't seem to get any response as the alert at success doesn't popup. I've debugged using the browser's network console and it return the expected response but it doesn't seem to reach the success function in the JavaScript code. Any insights or suggestions are welcome. Thanks.
In case you are still interested in the answer, try this before doing the request
var data = { firstName: 'stack', lastName: 'overflow' };
var jsonData = JSON.stringify(data);
and change your AJAX request to
$.ajax({
type: "POST",
url: "fHandler.ashx",
data: jsonData,
dataType: 'json',
contentType: 'application/json; charset-utf-8'
})
.done(function (response) {
// do something nice
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log("request error");
console.log(textStatus);
console.log(errorThrown);
});
Explanation
You are trying to send the plain data object. You must transform it into a Json string using JSON.stringify(object).
Changing the dataType isn't really a solution but a workaround.
Additional Notes
Also, I think you should use .done() and .fail(). See here for further details.

Categories

Resources