I have created a jQuery code which will take a form(which is in my view) and it will serialize it and it will post that to my controller.......Jquery code looks like this......
$(document).ready(function () {
$('#submit').click(function () {
var jsonObj = $('#form').serialize();
$.ajax({
type: "POST",
url: "../Home/Index",
data: JSON.stringify({ "cus": jsonObj }),
success: function(data){
alert(data + "done");
},
error:function(){
alert("Error!!!!");
}
});
});
});
This is how my controller method looks like:..........
[HttpPost]
public ActionResult Index(Customer cus)
{
string str = null;
if (cus.Name == "jude")
str = "Success";
else
str = "Error!!";
return Json(str);
}
Now i need to undo the serialization inside my controller method......can someone please give me an idea to do this..........
I have tried two ways to do this but didn't work.....
1 - var model = (Customer)cus.Deserialize();
2 - JavaScriptSerializer js = new JavaScriptSerializer();
var cus1 = js.Deserialize<Customer>(cus);
Related
I am currently trying to pass data from AJAX to Controller, however, the model always shows up empty/count = 0.
AJAX call:
$("#btnSubmit").click(function(e) {
e.preventDefault();
var _this = $(this);
var url = _this.closest("form").attr("action");
var rows = [];
var items = $(".itemRow");
$.each(items, function(i, item) {
var tbOne = $(item).find("input[name='tbOne']").val();
var tbTwo = $(item).find("input[name='tbTwo']").val();
var row = {
Test1: tbOne,
Test2: tbTwo
};
rows.push(row);
});
//Let's post to server
$.ajax({
type: "POST",
url: url,
data: rows,
contentType: "application/json"
})
.done(function(result) {
//do something with the result
})
});
});
Model:
public class Test
{
public string Test1 {get; set;}
public string Test2 {get; set;}
}
Controller:
[HttpPost]
public ActionResult Insert(<SomeOtherModel> otherModel, IEnumerable<Test> model)
{
foreach (var item in model)
{
// to do here
}
}
I am not sure what I am missing... I tried to search on other posts and they did relatively the same thing as I did. But I just can't get the data to my controller..
Firstly,you passed one model to controller,so the Action should have only one parameter.Furthermore,your contentType is"application/json",and you data is not json data.Besides,if you want to pass json data to controller,you need to use [FromBody].
Here is a demo worked:
Controller:
[HttpGet]
public ActionResult Insert()
{
return View();
}
[HttpPost]
public ActionResult Insert([FromBody]IEnumerable<Test> model)
{
return View();
}
View:
#{
ViewData["Title"] = "Insert";
}
<h1>Insert</h1>
<button id="btnSubmit">submit</button>
#section scripts{
<script type="text/javascript">
$("#btnSubmit").click(function () {
var rows = new Array();
var row = {};
row.Test1 = "test1";
row.Test2 = "test2";
rows.push(row);
var row1 = {};
row1.Test1 = "test11";
row1.Test2 = "test21";
rows.push(row1);
var model = JSON.stringify(rows);
//Let's post to server
$.ajax({
type: "POST",
url: "Insert",
data: model,
contentType: "application/json; charset=utf-8"
});
});
</script>
}
Result:
I have two <p> fields where I need to assign text
Here is html code:
<p id="appId" style="visibility: hidden;"></p>
<p id="calculationId" style="visibility: hidden;"></p>
I make AJAX call like this
$('#openCalculationConsumables').click(function() {
addConsumables();
});
function addConsumables() {
var patientName = $('#patientsId').val();
var finding = $('#findingvalue').val();
var procedure = $('#procedurevalue').val();
var model = {
findingValue: finding,
procedureValue: procedure,
patientId:patientName
}
$.ajax({
url: '#Url.Action("AddIndividualCalculation", "Calculations")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(model),
type: 'POST',
dataType: 'json',
processData: false,
success: function (data) {
$('#masters_data').load('#Url.Action("IndividualCalculationConsumables", "Calculations")', function() {
var list = data;
$('#calculationId').text(list[0].calcid);
$('#appId').text(list[0].appid);
});
}
});
}
And here is my back end code:
public JsonResult AddIndividualCalculation(string findingValue, string procedureValue,int patientId)
{
using (var ctx = new ApplicationDbContext())
{
Calculation calc = new Calculation
{
};
ctx.Calculations.Add(calc);
ctx.SaveChanges();
int calculationId = calc.Id;
Appointment app = new Appointment
{
Calculation_id = calculationId,
FindingContent = findingValue,
ProcedureContent = procedureValue,
Patient_id = patientId
};
ctx.Appointments.Add(app);
ctx.SaveChanges();
int appointmentId = app.Id;
var items = new
{
appid = appointmentId,
calcid = calculationId
};
return Json(items,JsonRequestBehavior.AllowGet);
}
}
I set breakpoint and see , that I have values in items. In console log I have this {appid: 1006, calcid: 1006}
But I cant assign it to <p> and have this error.
Cannot read property 'calcid' of undefined
Where is my problem?
Thank's for help.
$('#masters_data').load('#Url.Action("IndividualCalculationConsumables", "Calculations")', function() {
var list = data;
$('#calculationId').text(list[0].calcid);
$('#appId').text(list[0].appid);
});
list[0] is not defined as you are returning just an anonymous object not a list of objects
new {
appid = appointmentId,
calcid = calculationId
};
I get result of PartialViewResult in asp.net mvc project via ajax.When Model is null ! I pass nothing in partialViewResult but I get newline in result of ajax.How can i detect it by js?
var GetSuns = function (btn) {
$('body').append('<div class="WrapProgress"><img class="loadingimg vertical-middle-image" src="/Content/Travelo/images/travelenter_process_Art.gif" /></div>');
var urn = $(btn).data('urn');
var method = $(btn).data('method');
$.ajax({
url: '/art/ShowTime',
data: { s: urn, method: method },
type: "POST",
success: function (result) {
if (result.trim) {
console.log("1"+result+"1")
$('.WrapProgress').remove();
$('#ModalSuns .modal-body').html(result);
$('#ModalSuns').modal('show');
} else {
$('#Modal').modal('show');
}
},
error: function (jqXhr, textStates, errorThrown) {
console.log(errorThrown);
$('.WrapProgress').remove();
}
});
};
The issue with your code is anyway the result.trim need to changed to result.trim() inorder to trim the result string for any trailing spaces or linebreaks.
In order to detect line breaks in your code
text = `
`;
numberOfLineBreaks = (text.match(/\n/g)||[]).length;
console.log(numberOfLineBreaks)
I would like to bind the data from splunk to a dropdown list.
The servlet return a JsonString by gson
Gson gson = new Gson();
String jsonString = gson.toJson(arrays);
resp.getWriter().write(jsonString);
In the jsp, ajax was used to get back the jsonString and blind in drop down list.
$(document).ready(function() {
$.ajax({
type: "POST",
dataType : "json",
url : "../getName",
success : function(data) {
console.log("success to return name");
if (msg) {
alert("Somebody" + name + " was added in list !");
location.reload(true);
} else {
alert("Cannot add to list !");
}
$.each(objdata["wlsDomain"], function(i, val) {
jQuery('#DropdownList').append('<option value="' + val.name + '</option>');
});
};
)};
)];
It said $(...).ready is not a function. If I change the "$" to "jQuery", then there is no warning. However, binding is failed.
Then I have also tried the below code for knowing whether the ajax is workable.
And it showed "Fail". Therefore, the ajax is not workable.
jQuery(document).ready(function() {
var promise =jQuery.ajax({
type: "POST",
url: "../getName",
dataType: "json"
});
promise.fail( function() {
window.alert("Fail!");
});
promise.done( function() {
window.alert("Success!");
});
May I know what's wrong with this?
And how can I bind the name get from splunk to a dropdown list?
Thanks!
Try the following code:
$(document).ready(function () {
var $el = $('#DropdownList');
var url = "../getName";
$.getJSON(url, {}, function (data) {
$el.empty(); // remove old options
$.each(data, function(index, obj) {
$el.append($("<option></option>")
.attr("value", obj.name).text(obj.name));
});
} );
});
hey guys i read some of the other posts and tried alot but its still not working for me.
when i alert the array i get all the results on the first site but after sending the data to php i just get an empty result. any ideas?
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
window.location = "foo.php";
});
});
Php
$data = json_decode($_POST['data']);
THANK YOUU
my array looks something like this when i alert it house/flat,garden/nature,sports/hobbies
this are a couple of results the user might choose (from checkboxes).
but when i post it to php i get nothing. when i use request marker (chrome extension) it shows me something likethat Raw data cats=%5B%22house+themes%22%2C%22flat+items%22%5D
i also tried this way-- still no results
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
alert(cats);
$.ajax({
type: 'POST',
url: "foo.php",
data: {cats: JSON.stringify(cats)},
success: function(data){
alert(data);
}
});
});
window.location = "foo.php";
});
});
php:
$json = $_POST['cats'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
echo "<pre>";
print_r($data);
its drives me crazy
Take this script: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
so now your code is
$(document).ready(function() {
$('#Btn').click(function() {
var cats = [];
$('#cats input:checked').each(function() {
cats.push(this.value);
});
var st = JSON.stringify(cats);
$.post('foo.php',{data:st},function(data){cats : cats});
// window.location = "foo.php"; // comment this by this page redirect to this foo.php
});
});
//and if uou want toredirect then use below code
-------------------------------------------------
$.post('foo.php',{data:st},function(data){
window.location = "foo.php";
});
---------------------------------------------------
Php
$data = json_decode($_POST['data']);
var ItemGroupMappingData = []
Or
var ItemGroupMappingData =
{
"id" : 1,
"name" : "harsh jhaveri",
"email" : "test#test.com"
}
$.ajax({
url: 'url link',
type: 'POST',
dataType: "json",
data: ItemGroupMappingData,
success: function (e) {
// When server send response then it will be comes in as object in e. you can find data //with e.field name or table name
},
error: function (response) {
//alert(' error come here ' + response);
ExceptionHandler(response);
}
});
Try this :-
$data = json_decode($_POST['data'], TRUE);
I think you should move the "window.location = " to the post callback, which means it should wait till the post finshed and then redirect the page.
$.post('foo.php', {
data : st
}, function(data) {
window.location = "foo.php";
});