Get multiple strings from json controller result ajax - c#

I have a button sending an input from a text field in a form to my mvc controller using ajax. I now want the controller to return 2 strings as a json, and fill those strings into html inputs.
Controller
[HttpPost]
public ActionResult getName(string Name)
{
string SecondString = "secondString";
return Json(Name, SecondString);
}
View
<script>
$(document).ready(function () {
$("#btnGet").click(function () {
$.ajax(
{
type: "POST",
url: "home/getName",
data: {
Name: $("#txtName").val()
},
success: function (result) {
$('#FirstTextFieldToFill').val(result);
$('#SecondTextFieldToFill').val(result);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});

You're wrongly assigned parameters to the Json() method to return response of JsonResult, because the second parameter is JsonRequestBehavior or contentType. You should return Controller.Json() response with single parameter like this:
[HttpPost]
public ActionResult GetName(string Name)
{
string SecondString = "secondString";
return Json(new { Name = Name, SecondString = SecondString });
}
And then modify your AJAX call to return 2 strings from response by using property names:
$("#btnGet").click(function () {
$.ajax({
type: "POST",
url: "#Url.Action("GetName", "Home"),
data: { Name: $("#txtName").val() },
success: function (result) {
$('#FirstTextFieldToFill').val(result.Name);
$('#SecondTextFieldToFill').val(result.SecondString);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});

Worked like this:
Controller
[HttpPost]
public ActionResult getName(string Name)
{
string SecondString = "secondString";
return Json(new { Name, SecondString });
}
View
<script>
$(document).ready(function () {
$("#btnGet").click(function () {
$.ajax(
{
type: "POST",
url: "home/getName",
data: {
Name: $("#txtName").val()
},
success: function (result) {
$('#FirstTextFieldToFill').val(result.Name);
$('#SecondTextFieldToFill').val(result.SecondString);
$('#SecondTextFieldToFill').show();
$('#FirstTextFieldToFill').show();
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});

For this you should create a class having two string eg.
public class example
{
public string FirstString {get; set;}
public string SecondString {get; set;}
}
create object of the class in the controller and add the strings to it serialize to json and return
[HttpPost]
public ActionResult getName(string Name)
{
example eg=new example();
eg.FirstString ="your first string";
eg.SecondString ="your second string";
string jsonString= JsonConvert.SerializeObject(eg);
return Json(jsonString);
}
JS file should extract the strings from the json object
<script>
$(document).ready(function () {
$("#btnGet").click(function () {
$.ajax(
{
type: "POST",
url: "home/getName",
data: {
Name: $("#txtName").val()
},
success: function (result) {
var jsonResult=JSON.parse( result );
$('#FirstTextFieldToFill').val(jsonResult.FirstString);
$('#SecondTextFieldToFill').val(jsonResult.SecondString);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
Dependency required in controller are
JsonConvert is from the namespace Newtonsoft.Json
Use NuGet to download the package
"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install"

Related

how to fix this my following code is not working

I am trying to post a data and trying to return from controller to back again and show it to alert box but dont know why this is not working
here is the controller code
[HttpPost]
public ActionResult getRequirmentsByProject(string projectname)
{
return Json(projectname, JsonRequestBehavior.AllowGet);
}
and here is my front end code
<input id="projName" type="text" name="Name" required="" value="javascript">
and this is my script code
var projectname = document.getElementById('projName').value;
$.ajax({
url: '/Worksheet/getRequirmentsByProject',
type: 'post',
data: { projectname },
contentType: 'application/json; charset=utf-8',
success: function (html) {
alert(html);
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
In your case, I am giving you a simple example on how you can POST your form variables to your controller using AJAX:
<script type="text/javascript">
var projectname = document.getElementById('projName').value;
var json = {
projectname: projectname
};
$.ajax({
url: '#Url.Action("getRequirmentsByProject", "Worksheet")',
type: 'post',
dataType: "json",
data: { "json": JSON.stringify(json)},
success: function (data) {
alert(data);
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
</script>
And in your controller, you can get this value as:
using System.Web.Script.Serialization;
[HttpPost]
public ActionResult getRequirmentsByProject(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
string projectname= jsondata["projectname"];
return Json(projectname);
}
its httpget and writing with a wrong way
[HttpGet]
public ActionResult getRequirmentsByProject(string projectname)
{
return Json(projectname, JsonRequestBehavior.AllowGet);
}
this is the right way thankyou for pointing out

How to show custom error message on forced error inside a JsonResult

I have a JsonResult where I do some validation and set the response status code to 400 and return a Json with a custom variable named errorMessage.
In the view I have the normal JQuery AJAX code, and in the error section I want to access to the value in the variable errorMessage.
How to declare the function() inside the error section in JQuery AJAX code.
// JsonResult action method
public JsonResult QuitarMiembro(string Id)
{
if (Id == null)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { errorMessage = "Null Id" });
}
}
//JQuery AJAX
function MyFun(Id) {
console.log(Id);
$.ajax({
type: "POST",
url: '#Url.Action("QuitarMiembro", "MiembrosJD")',
dataType: 'json',
data: { IdUsuario: Id },
success: function (data) {
fnMostrarMensajeExito(data.message);
tablaMiembrosJD.ajax.reload();
},
error: function (data) {
console.log(data.errorMessage);
}
});
}
try this code for error msg
function MyFun(Id) {
console.log(Id);
$.ajax({
type: "POST",
url: '#Url.Action("QuitarMiembro", "MiembrosJD")',
dataType: 'json',
data: { IdUsuario: Id },
success: function (data) {
fnMostrarMensajeExito(data.message);
tablaMiembrosJD.ajax.reload();
},
error: function (data) {
alert("Error:" + data.errorMessage);`
}
});
}

Retrieving data from Ajax POST in asp.net

I have an ajax POST like this
$(document).ready(function () {
var pcontent = document.body.innerHTML;
var url = new URI();
$.ajax({
url: url,
type: "POST",
data: { "pcontent": pcontent },
success: function (data) {
alert($(data).find(".right-panel").html());
},
complete: function () {
},
error: function (jqXHR, error, errorThrown) {
if (jqXHR.status) {
alert(jqXHR.responseText);
} else {
alert("Something went wrong");
}
}
});
return false;
});
I am little confused how i could retrieve data (pcontent) that i post here in my code behind.actually in a specific class file i need to implement this logic .
You have to create a controller action:
public class HomeController: {
// model
public class PDocument {
public string pcontent {get;set;}
}
[HttpPost]
public ActionResult SaveDocument(PDocument pcontent){
// do something
return new JsonResult() { Data = new { Success = true } };
}
}
JS:
$.ajax({
url: "Home/SaveDocument",
type: "POST",
data: { "pcontent": pcontent}
...});
Note:
You don't need to create a model on server if set
$.ajax({
url: "Home/SaveDocument",
type: "POST",
data: pcontent
});
// server side
public ActionResult SaveDocument(string pcontent){
// do some thing
}
For security reason, your html must be encoded before calling ajax
In case you new to mvc, then this is a good way to start: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-controller

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

I'm trying to pass an array of objects into an MVC controller method using
jQuery's ajax() function. When I get into the PassThing() C# controller method,
the argument "things" is null. I've tried this using a type of List for
the argument, but that doesn't work either. What am I doing wrong?
<script type="text/javascript">
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Xhr/ThingController/PassThing',
data: JSON.stringify(things)
});
});
</script>
public class ThingController : Controller
{
public void PassThing(Thing[] things)
{
// do stuff with things here...
}
public class Thing
{
public int id { get; set; }
public string color { get; set; }
}
}
Using NickW's suggestion, I was able to get this working using things = JSON.stringify({ 'things': things }); Here is the complete code.
$(document).ready(function () {
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
things = JSON.stringify({ 'things': things });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Home/PassThings',
data: things,
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
$('#result').html(response);
}
});
});
public void PassThings(List<Thing> things)
{
var t = things;
}
public class Thing
{
public int Id { get; set; }
public string Color { get; set; }
}
There are two things I learned from this:
The contentType and dataType settings are absolutely necessary in the ajax() function. It won't work if they are missing. I found this out after much trial and error.
To pass in an array of objects to an MVC controller method, simply use the JSON.stringify({ 'things': things }) format.
Couldn't you just do this?
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
$.post('#Url.Action("PassThings")', { things: things },
function () {
$('#result').html('"PassThings()" successfully called.');
});
...and mark your action with
[HttpPost]
public void PassThings(IEnumerable<Thing> things)
{
// do stuff with things here...
}
I am using a .Net Core 2.1 Web Application and could not get a single answer here to work. I either got a blank parameter (if the method was called at all) or a 500 server error. I started playing with every possible combination of answers and finally got a working result.
In my case the solution was as follows:
Script - stringify the original array (without using a named property)
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: mycontrolleraction,
data: JSON.stringify(things)
});
And in the controller method, use [FromBody]
[HttpPost]
public IActionResult NewBranch([FromBody]IEnumerable<Thing> things)
{
return Ok();
}
Failures include:
Naming the content
data: { content: nodes }, // Server error 500
Not having the contentType = Server error 500
Notes
dataType is not needed, despite what some answers say, as that is used for the response decoding (so not relevant to the request examples here).
List<Thing> also works in the controller method
Formatting your data that may be the problem. Try either of these:
data: '{ "things":' + JSON.stringify(things) + '}',
Or (from How can I post an array of string to ASP.NET MVC Controller without a form?)
var postData = { things: things };
...
data = postData
I have perfect answer for all this : I tried so many solution not able to get finally myself able to manage , please find detail answer below:
$.ajax({
traditional: true,
url: "/Conroller/MethodTest",
type: "POST",
contentType: "application/json; charset=utf-8",
data:JSON.stringify(
[
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
]),
success: function (data) {
$scope.DisplayError(data.requestStatus);
}
});
Controler
public class Thing
{
public int id { get; set; }
public string color { get; set; }
}
public JsonResult MethodTest(IEnumerable<Thing> datav)
{
//now datav is having all your values
}
The only way I could get this to work is to pass the JSON as a string and then deserialise it using JavaScriptSerializer.Deserialize<T>(string input), which is pretty strange if that's the default deserializer for MVC 4.
My model has nested lists of objects and the best I could get using JSON data is the uppermost list to have the correct number of items in it, but all the fields in the items were null.
This kind of thing should not be so hard.
$.ajax({
type: 'POST',
url: '/Agri/Map/SaveSelfValuation',
data: { json: JSON.stringify(model) },
dataType: 'text',
success: function (data) {
[HttpPost]
public JsonResult DoSomething(string json)
{
var model = new JavaScriptSerializer().Deserialize<Valuation>(json);
This is how it works fine to me:
var things = [
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
];
$.ajax({
ContentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Controller/action',
data: { "things": things },
success: function () {
$('#result').html('"PassThings()" successfully called.');
},
error: function (response) {
$('#result').html(response);
}
});
With "ContentType" in capital "C".
This is working code for your query,you can use it.
Controler
[HttpPost]
public ActionResult save(List<ListName> listObject)
{
//operation return
Json(new { istObject }, JsonRequestBehavior.AllowGet); }
}
javascript
$("#btnSubmit").click(function () {
var myColumnDefs = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
myColumnDefs.push({ 'Status': true, 'ID': $(this).data('id') })
} else {
myColumnDefs.push({ 'Status': false, 'ID': $(this).data('id') })
}
});
var data1 = { 'listObject': myColumnDefs};
var data = JSON.stringify(data1)
$.ajax({
type: 'post',
url: '/Controller/action',
data:data ,
contentType: 'application/json; charset=utf-8',
success: function (response) {
//do your actions
},
error: function (response) {
alert("error occured");
}
});
I can confirm that on asp.net core 2.1, removing the content type made my ajax call work.
function PostData() {
var answer = [];
for (let i = 0; i < #questionCount; i++) {
answer[i] = $(`#FeedbackAnswer${i}`).dxForm("instance").option("formData");
}
var answerList = { answers: answer }
$.ajax({
type: "POST",
url: "/FeedbackUserAnswer/SubmitForm",
data: answerList ,
dataType: 'json',
error: function (xhr, status, error) { },
success: function (response) { }
});
}
[HttpPost]
public IActionResult SubmitForm(List<Feedback_Question> answers)
{}
Wrapping your list of objects with another object containing a property that matches the name of the parameter which is expected by the MVC controller works.
The important bit being the wrapper around the object list.
$(document).ready(function () {
var employeeList = [
{ id: 1, name: 'Bob' },
{ id: 2, name: 'John' },
{ id: 3, name: 'Tom' }
];
var Employees = {
EmployeeList: employeeList
}
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Employees/Process',
data: Employees,
success: function () {
$('#InfoPanel').html('It worked!');
},
failure: function (response) {
$('#InfoPanel').html(response);
}
});
});
public void Process(List<Employee> EmployeeList)
{
var emps = EmployeeList;
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
var List = #Html.Raw(Json.Encode(Model));
$.ajax({
type: 'post',
url: '/Controller/action',
data:JSON.stringify({ 'item': List}),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//do your actions
},
error: function (response) {
alert("error occured");
}
});
Removing contentType just worked for me in asp.net core 3.1
All other methods failed
If you are using ASP.NET Web API then you should just pass data: JSON.stringify(things).
And your controller should look something like this:
public class PassThingsController : ApiController
{
public HttpResponseMessage Post(List<Thing> things)
{
// code
}
}
Modification from #veeresh i
var data=[
{ id: 1, color: 'yellow' },
{ id: 2, color: 'blue' },
{ id: 3, color: 'red' }
]; //parameter
var para={};
para.datav=data; //datav from View
$.ajax({
traditional: true,
url: "/Conroller/MethodTest",
type: "POST",
contentType: "application/json; charset=utf-8",
data:para,
success: function (data) {
$scope.DisplayError(data.requestStatus);
}
});
In MVC
public class Thing
{
public int id { get; set; }
public string color { get; set; }
}
public JsonResult MethodTest(IEnumerable<Thing> datav)
{
//now datav is having all your values
}
What I did when trying to send some data from several selected rows in DataTable to MVC action:
HTML
At the beginning of a page:
#Html.AntiForgeryToken()
(just a row is shown, bind from model):
#foreach (var item in Model.ListOrderLines)
{
<tr data-orderid="#item.OrderId" data-orderlineid="#item.OrderLineId" data-iscustom="#item.IsCustom">
<td>#item.OrderId</td>
<td>#item.OrderDate</td>
<td>#item.RequestedDeliveryDate</td>
<td>#item.ProductName</td>
<td>#item.Ident</td>
<td>#item.CompanyName</td>
<td>#item.DepartmentName</td>
<td>#item.ProdAlias</td>
<td>#item.ProducerName</td>
<td>#item.ProductionInfo</td>
</tr>
}
Button which starts the JavaScript function:
<button class="btn waves-effect waves-light btn-success" onclick="ProcessMultipleRows();">Start</button>
JavaScript function:
function ProcessMultipleRows() {
if ($(".dataTables_scrollBody>tr.selected").length > 0) {
var list = [];
$(".dataTables_scrollBody>tr.selected").each(function (e) {
var element = $(this);
var orderid = element.data("orderid");
var iscustom = element.data("iscustom");
var orderlineid = element.data("orderlineid");
var folderPath = "";
var fileName = "";
list.push({ orderId: orderid, isCustomOrderLine: iscustom, orderLineId: orderlineid, folderPath: folderPath, fileName : fileName});
});
$.ajax({
url: '#Url.Action("StartWorkflow","OrderLines")',
type: "post", //<------------- this is important
data: { model: list }, //<------------- this is important
beforeSend: function (xhr) {//<--- This is important
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
showPreloader();
},
success: function (data) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
complete: function () {
hidePreloader();
}
});
}
}
MVC action:
[HttpPost]
[ValidateAntiForgeryToken] //<--- This is important
public async Task<IActionResult> StartWorkflow(IEnumerable<WorkflowModel> model)
And MODEL in C#:
public class WorkflowModel
{
public int OrderId { get; set; }
public int OrderLineId { get; set; }
public bool IsCustomOrderLine { get; set; }
public string FolderPath { get; set; }
public string FileName { get; set; }
}
CONCLUSION:
The reason for ERROR:
"Failed to load resource: the server responded with a status of 400 (Bad Request)"
Is attribute: [ValidateAntiForgeryToken] for the MVC action StartWorkflow
Solution in Ajax call:
beforeSend: function (xhr) {//<--- This is important
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
To send List of objects you need to form data like in example (populating list object) and:
data: { model: list },
type: "post",
Nothing worked for me in asp.net core 3.1. Tried all the above approaches.
If nothing is working and someone is reading the rows from table
and wanted to pass it to Action method try below approach...
This will definitely work...
<script type="text/javascript">
$(document).ready(function () {
var data = new Array();
var things = {};
// make sure id and color properties match with model (Thing) properties
things.id = 1;
things.color = 'green';
data.push(things);
Try the same thing for dynamic data as well that is coming from table.
// var things = [ { id: 1, color: 'yellow' }, { id: 2, color: 'blue' }, { id: 3, color: 'red' } ];
$.ajax({
contentType: 'application/json;',
type: 'POST',
url: 'your url goes here',
data: JSON.stringify(things)
});
});
</script>
public class ThingController : Controller
{
public void PassThing([FromBody] List<Thing> things)
{
// do stuff with things here...
}
public class Thing
{
public int id { get; set; }
public string color { get; set; }
}
}
The way that worked for me
$.ajax({
url: '#Url.Action("saveVideoesCheckSheet", "checkSheets")',
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: "data=" + JSON.stringify(videos),
success: function (response) {
window.location.reload(true);
},
failure: function (msg) {
}
});
});
Controller
public string saveVideoesCheckSheet(string data)
{
List<editvideo> lst = JsonConvert.DeserializeObject<List<editvideo>>(data);...}
After much experimentation, bit of a cheat.

pass in filename into controller

i am trying to pass in a filename as a requestparameter into a controller, but it returns with an invalid request?
$(document).ready(function (event) {
$('#btnTask').click(function () {
$.ajax({
url: "/Home/Sometask/",
data: "c:\\somefile.txt",
async: false,
success: function (data) { alert(data); }
});
event.preventDefault;
});
});
public string Sometask(string id)
{
return "ready";
}
Use data: { filename: "c:\\somefile.txt" }
You have to give a variable name for the post data so your controller know how to map the value.

Categories

Resources