I am doing below to pass Json data to My MVC controller action
Script
var jInput = $("textarea");
var count = 0;
var jsonPackage = "{";
$.each(jInput, function (i) {
jInput[i].style.borderColor = "";
if (jInput[i].value != "") {
if (count != 0) {
jsonPackage += ",";
}
count++;
jsonPackage += "'" + jInput[i].id + "':'" + jInput[i].value.replace(/\\/g, "|").replace(/\'/g, "^") + "'";
}
});
jsonPackage += "}";
$.ajax({
url: "Appraisal/LegalCheck",
type: "POST",
data: JSON.stringify(jsonPackage),
dataType: "json",
contentType: "application/json",
success: function (retValue) {
alert(retValue);
}
});
Controller method
public Dictionary<string, Illegal[]> LegalCheck(string jsonPackage)
{
}
Class
[Serializable]
public class Illegal
{
public string Phrase { get; set; }
public int StartIndex { get; set; }
}
For some reason jsonPackage is always null in the controller method. Sample data that s being passed from the script is,
jsonPackage - {'CommentTextarea_1181_1183':'ghhgghhhgd','CommentTextarea_1181_1184':'Coments','CommentTextarea_1181_1185':'comentss'}
What am I doing wrong here? Why am I getting null in my controller method? Please suggest.
Thanks
try
$.ajax({
url: "Appraisal/LegalCheck",
type: "POST",
data: {jsonPackage:JSON.stringify(jsonPackage)},
dataType: "json",
success: function (retValue) {
alert(retValue);
}
});
I would guess your JSON string isnt actually being assigned to the jsonPackage variable and so isnt being picked up by your model binder.
for a quick fix try
$.ajax({
url: "Appraisal/LegalCheck",
type: "POST",
data: "jsonPackage="+JSON.stringify(jsonPackage),
dataType: "json",
contentType: "application/json",
success: function (retValue) {
alert(retValue);
}
});
Related
I am new in ASP.NET Core. I just want to simply load a JSON file's data into a listbox.
Here is the controller class:
public class EmployeeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetEmpList()
{
var empList = new List<Employee>()
{
new Employee { Id=1, Name="Manas"},
new Employee { Id=2, Name="Tester"}
};
return Json(empList);
}
}
And here is the view:
<select id="ddlEmployees"></select>
<script>
var ddlEmployees = $("#ddlEmployees");
$.ajax({
type: "GET",
url: "/EmployeeController/GetEmpList",
dataType: 'JSON',
contentType: "application/json",
success: function (data) {
alert(data);
for (var i = 0; i < data.length; i++) {
ddlEmployees.append('<option> ' + data[i] + '</option >');
}
}
}); </script>
Assuming that you are successfully able to make requests to your API endpoint I think the part that needs to be updated is actually your jQuery in the view. Since you're returning a list as JSON, what you'll have in your data argument is an array of objects. So in order to populate the values of the <option> tag with the values in your JSON object, you'll need to access the JSON fields that you define in your Controller.
<select id="ddlEmployees"></select>
<script>
var ddlEmployees = $("#ddlEmployees");
$.ajax({
type: "GET",
url: "/EmployeeController/GetEmpList",
dataType: 'JSON',
contentType: "application/json",
success: function (data) {
alert(data);
for (var i = 0; i < data.length; i++) {
ddlEmployees.append('<option value="' + data[i].Id + '"> ' + data[i].Name + '</option >');
}
}
}); </script>
The naming convention for response json in asp.net core is camel case instead of pascal case.
You could add console.log(data) to check the response in Console panel(press F12 in browser). Then you will find the property name in response is camel case.
Change like below:
$.ajax({
type: "GET",
url: "/Employee/GetEmpList", //it should be Employee/xxx instead of EmployeeController/xxx
dataType: 'JSON',
contentType: "application/json",
success: function (data) {
console.log(data);
for (var i = 0; i < data.length; i++){
ddlEmployees.append('<option value="' + data[i].id + '"> ' + data[i].name + '</option >');
}
}
});
I have a view that adds an Unordered list and list items to it at runtime, then I loop through to get the entered values, push the info to an object, and do the Ajax call to my method.
I always get an empty parameter on the controller, the console.log(assetWeighJsonDetail) shows what was entered, so I'm making sure I'm not passing and empty object (see the image below):
// Client side script:
var assetSerialNumber = "";
var weight = 0;
var assetWeighJsonDetail = [];
$(".ul-asset-weigh").each(function () {
var classNameSelected = this.id;
$("." + classNameSelected).each(function () {
assetSerialNumber = $(this).attr('id');
weight = $(this).val();
assetWeighJsonDetail.push({
OriginID: classNameSelected,
AssetSerialNumber: assetSerialNumber,
Weight: weight
});
});
});
console.log(assetWeighJsonDetail);
$.ajax({
url: "/AssetWeigh/SaveAssetWeigh",
data: JSON.stringify({assetWeighJsonDetail}),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
if (response) {
alert("success");
}
else {
alert("fail");
}
},
error: function (exception) {
}
});
// Console:
// Controller Method:
[HttpPost]
public ActionResult SaveAssetWeigh(List<AssetWeighJsonDetail> assetWeighJsonDetail)
{
bool success = false;
success = assetWeighJsonDetail != null && assetWeighJsonDetail.Count > 0;
return Json(success);
}
// Method's class List parameter:
public class AssetWeighJsonDetail
{
public int OriginID { get; set; }
public string AssetSerialNumber { get; set; }
public decimal Weight { get; set; }
}
You should try with $.post I have faced the same issue if using $.ajax and was not working and just switching to $.post made it work.
$.post( "/AssetWeigh/SaveAssetWeigh", parameters, function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
I'm on my phone and can't type all of it, I'll try to update later from my computer
This is my script:
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
function btnadHocSave() {
debugger
var lv_header = $("#Header").serializeObject(); // this is header <fieldset> tag
var lv_detail = $("#SubmitMachine").serializeObject(); // this is detail <fieldset> tag
$.ajax({
type: "POST",
url: '#Url.Action("UpdateMachine")',
contentType: "application/json",
dataType: "JSON",
data: {
myheader: lv_header,
mydetail: lv_detail
},
cache: false,
success: function (data) {
alert("Success!..");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
})
}
This is my action code. PMAllotmentEntry and PMAllotmentDetailEntry are models:
public ActionResult UpdateMachine(PMAllotmentEntry myheader, PMAllotmentDetailEntry mydetail)
{
return View();
}
Now my problem I'm not able get the values from view to controller.
I tried JSON.stringify also but there is no use.
It is working If I pass single JSON value.
I tried out all the possibilities. Did as you said also but no use. Finally I did the following. I got two JSON values but still facing a issues because JSON second values first field value coming with first JSON values.
function btnadHocSave() {
debugger
var lv_header = $("#Header").serialize(); // this is header <fieldset>
var lv_detail = $("#SubmitMachine").serialize();
$.ajax(
{
type: "GET",
url: '/PMAllotments/UpdateMachine',
contentType: "application/json",
dataType: "JSON",
data: lv_header + ',' + lv_detail,
success: function (data) {
alert("Success!..");
debugger
$("#adHocAdd40").modal("hide");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
})
}
Now I'm removed JQuery from cshtml file and simply used post method
[HttpPost]
public ActionResult UpdateMachine(PMAllotmentEntry m)
{
//complete the task
return View();
}
replaced foreach loop in .cshtml file with for loop
FOR loop is highly important foreach loop never return your child model data.
#for (int a = 0; a < Model.PMAllotmentDetail.Count; a++)
{
#* table rows here *#
}
My Model as following
[NotMapped]
public class PMAllotmentEntry
{
[Key]
public Int64 PMAllotmentId { get; set; }
[Required (ErrorMessage ="Add atleast one machine!")]
public List<PMAllotmentDetailEntry> PMAllotmentDetail { get; set; }
}
[NotMapped]
public class PMAllotmentDetailEntry
{
[Key]
public Int64 PMAllotmentDetailId { get; set; }
[ForeignKey("PMAllotmentId")]
public Int64 PMAllotmentId { get; set; }
}
I have a controller which return a model as json object:
[HttpGet("{id}")]
[Route("GetById")]
public async Task <JsonResult> GetById([FromQuery]string id)
{
var myfoo = new {foo="bar", baz="Blech"};
return Json(myfoo);
}
How can handle the returned json object in jQuery?
<script type="text/javascript">
$('#id').change(function () {
var id = $('#id').val();
if (id.length = 17) {
$.ajax(
{
url: '/Home/GetById?id=' + id,
type: 'GET',
jsondata: "",
contentType: 'application/json; charset=utf-8',
success: function (jsondata) {
alert("foo is: " + jsondata ); <---?
},
error: function () {
//alert("error");
}
});
}
});
</script>
I need to get foo value and assigned to an html control
Thanks in advance
all the time I was using capital letter
jsondata.foo // not .Foo
I am getting parseerror for my below ajax call, what can be wrong?
<script type="text/javascript" src="json.js"></script>
var contact1 = {
"id":"5",
"name": "fsdfsd"
};
var jsonString = "{\"JsData\":" + JSON.stringify(contact1) + "}";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/ReceiveData",
data: jsonString,
// data: DTO,
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(response,ajaxOptions, thrownError) {
alert("error:" + ajaxOptions);
}
});
My server side webmethod is
[System.Web.Services.WebMethod]
public static string ReceiveData(contact1 JsData)
{
//JsonTextParser parser = new JsonTextParser();
//JsonObject obj = parser.Parse(JsData);
//foreach (JsonObject field in obj as JsonObjectCollection)
//{
// string v = field.ToString();
//}
return "success";
}
public class contact1
{
public int id;
public string name;
}
I got the solution. I am using 2.0 framework, I forgot to add Ajax related references in my web.config. I added those manually, & it worked.