I am trying to bind data from json. In the controller, I am sending
......
public JsonResult LoadTree()
........
return Json(jn, JsonRequestBehavior.AllowGet);
In debug I get the values in jn (47 items, each has two enteries (text and value).
In the view, I am using the following script:
function onDataBinding(e) {
var url = 'CourseCases/LoadTree';
var result;
$.ajax({
url: url,
data: {},
contentType: "application/json",
success: function (data) {
alert(data);
var treeview = $("#TreeView").data("tTreeView");
treeview.bindTo(data);
}
});
}
It does not work, alert shows object, object; and the treeview is blank!
Any idea why? Thanks in advance.
Actually the properties that you are sending should be called Value and Text instead of value and text. Here's an example that works fine for me.
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult LoadTree()
{
var jn = new[]
{
new { Value = "1", Text = "Item 1" },
new { Value = "2", Text = "Item 2" },
new { Value = "3", Text = "Item 3" },
};
return Json(jn, JsonRequestBehavior.AllowGet);
}
}
View (~/Views/Home/Index.cshtml):
<script type="text/javascript">
function onDataBinding(e) {
var url = '#Url.Action("LoadTree")';
var result;
$.ajax({
url: url,
data: { },
success: function (data) {
var treeview = $("#TreeView").data("tTreeView");
treeview.bindTo(data);
}
});
}
</script>
#(Html
.Telerik()
.TreeView()
.Name("TreeView")
.ClientEvents(events =>
{
events.OnDataBinding("onDataBinding");
})
)
Probably you should call treeview.bindTo in the callback method of $.post directly. I guess with the current code you might bind the treeview to jsonObject == jn before jn == content is ensured in the callback. If you alert you add a big delay and it gives the AJAX post enough time to complete and run the callback.
Related
I have a problem when I try to save some data to the database. I can see the ID and Date returning me appropriate values in the JS function... However, the parameter for the Process function inside the controller class remains null. I don't know why is that happening. There is a linq query that is also included in the Hello Model, but I didn't include it because there is no need for it.
Model:
public class Hello
{
List<string> Ids { get; set; }
List<string> Dates { get; set; }
}
Controller:
[HttpPost]
public ActionResult Process(string ids, string dates)
{
Hello model = new Hello();
if (ModelState.IsValid)
{
using (db = new DB())
{
rp = new RequestProcess();
//var c = rp.getHello(model, dates);
var c = rp.getStuff();
if (c != null)
{
foreach (var i in c)
{
if (i != null)
{
ids = i.ID;
dates = i.Date.ToString();
}
db.SaveChanges();
}
}
}
ViewBag.Message = "Success";
return View(model);
}
else
{
ViewBag.Message = "Failed";
return View(model);
}
}
View:
<td><input class="id" type="checkbox" id=#item.ID /></td>
<td>#Html.DisplayFor(x => #item.ID)</td>
<td><input class="date" id=date#item.ID type="text" value='#item.Date'/></td>
$(document).ready(function () {
var ids = "";
var dates = "";
$("#btnSubmit").bind("click", function () {
createUpdateArrays();
var url = "/Sample/Process";
$.ajax({
type: "POST",
url: url,
data: { ids: ids, dates: dates },
contentType: 'application/json; charset=utf-8',
success: function (success) {
if (success === true) {
alert("HERE WE ARE");
}
else {
alert("eror");
}
}
});
ids = "";
dates = "";
});
function createUpdateArrays() {
var i = 0;
$('input.remedy-id:checkbox').each(function () {
if ($(this).is(':checked')) {
var rid = $(this).attr("id");
$('.planned-date').each(function () {
var did = $(this).attr("id");
if (did === rid) {
var date = $(this).val();
ids += rid + ",";
dates += date + ",";
}
});
};
});
};
Any help would be appreciated!
I think you need contentType: 'application/json' in your $.ajax({});
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json'
});
Also, try adding [FromBody]Hello model in your controller action.
There are several issues in your code:
1) You're passing JSON string containing viewmodel properties, it is necessary to set contentType: 'application/json; charset=utf-8' option in AJAX callback to ensure model binder recognize it as viewmodel parameter.
2) return View() is not applicable for AJAX response, use return PartialView() instead and put html() to render response in target element.
Therefore, you should use AJAX setup as provided below:
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(list),
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#targetElement').html(result);
},
error: function (xhr, status, err) {
// error handling
}
});
Controller Action
[HttpPost]
public ActionResult Process(Hello model)
{
if (ModelState.IsValid)
{
using (db = new DB())
{
// save data
}
ViewBag.Message = "Success";
return PartialView("_PartialViewName", model);
}
else
{
ViewBag.Message = "Failed";
return PartialView("_PartialViewName", model);
}
}
Remember that AJAX callback intended to update certain HTML element without reloading entire view page. If you want to reload the page with submitted results, use normal form submit instead (with Html.BeginForm()).
I need to populate the ajax data attribute with one or many key value pairs to post up to a MVC controller action. The snag is that I want to use one js function to send data to different controller actions each with different signatures. Here goes:
MVC View
#{
var Params = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("param1","foo"),
new KeyValuePair<string, string>("param2","bar"),
};
var targetUrl = "/MyActionName/";
var myParams = #Json.Encode(Params);
var clickFunction = $"myFunction('{targetUrl}', {myParams})";
}
Do It
Javascript function
function myFunction(url, paramData) {
var dataParams = [];
paramData.forEach(function (arrayItem) {
var key = arrayItem.Key;
var value = arrayItem.Value;
dataParams[key] = value;
});
// This works
$.ajax({
url: url,
data: {
param1: "foo",
param2: "bar"
},
success: function (partialViewResult) {
$('#TargetDIV').html(partialViewResult);
},
});
// This doesn't
$.ajax({
url: url,
data: { dataParams },
success: function (partialViewResult) {
$('#TargetDIV').html(partialViewResult);
},
});
}
Controller Action Example 1
public PartialViewResult MyAction1(string param1, string param2)
{
....
}
Controller Action Example 2
public PartialViewResult MyAction2(string apple, string orange, string grape)
{
....
}
Controller Action Example 3
public PartialViewResult MyAction3(string pig, string cow, string dog, string cat)
{
....
}
I'd like myFunction to be used to post up to multiple controller actions with varying signatures. So i'd just need to throw a list of KeyValuePair at myFunction and will handle it.
Tried so far without any luck:
using JSON.stringify but is doesn't format dataParams in the correct way.
using a MVC model instead of many separate params. This is because the param names will be different so one model won't fit all scenarios
If I can get this to work i'd then extend it to handle data types other than string but for sake of simplicity i've stuck to string here
Any help would be very much appreciated
It is wrong dataParams you must to set is as an object
function myFunction(url, paramData) {
var dataParams = {};
paramData.forEach(function (arrayItem) {
var key = arrayItem.Key;
var value = arrayItem.Value;
dataParams[key] = value;
});
// This works
$.ajax({
url: url,
data: {
param1: "foo",
param2: "bar"
},
success: function (partialViewResult) {
$('#TargetDIV').html(partialViewResult);
},
});
// This doesn't
$.ajax({
url: url,
data: dataParams,
success: function (partialViewResult) {
$('#TargetDIV').html(partialViewResult);
},
});
}
I have a form in my view which has only one textarea input initially and user can add more textarea inputs if he wants with jquery. My problem is related to second case. After submitting the form i am getting an array of objects in console but when i am passing this array to mvc action in my controller it is coming to be null.
I have tried these solution but did not succeed:
Send array of Objects to MVC Controller
POST a list of objects to MVC 5 Controller
here is my code:-
jquery code:
$('body').on('submit', '#addTextForm', function () {
console.log($(this));
var frmData = $(this).serializeArray();
console.log(frmData);
$.ajax({
type: 'post',
url: '/Dashboard/UploadText',
contentType: 'application/json',
data: JSON.stringify({ obj: frmData }),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
return false;
});
MVC action:
[HttpPost]
public string UploadText(SliderTextList obj)
{
return "success";
}
my object class:
public class SliderText
{
[JsonProperty("Id")]
public int Id { get; set; }
[JsonProperty("SlideName")]
public string SlideName { get; set; }
[JsonProperty("Content")]
public string Content { get; set; }
}
public class SliderTextList
{
public List<SliderText> AllTexts { get; set; }
}
I have to store the Content in json file with Id and SlideName, so i think i have to pass a list object in mvc action Uploadtext which is coming out to be null always. Please help.
$(document).ready(function(){
$('body').on('submit', '#addTextForm', function () {
var listData=[];
var oInputs = new Array();
oInputs = document.getElementsByTag('input' );
var k=1;
for ( i = 0; i < oInputs.length; i++ )
{
if ( oInputs[i].type == 'textarea' )
{
var obj=new Object();
obj.Id=k;
obj.SlideName=oInputs[i].Name;
obj.Content=oInputs[i].Value;
K=parseInt(k)+1;
listData.push(obj);
}
}
$.ajax({
type: 'post',
url: '/Dashboard/UploadText',
contentType: 'application/json',
data: JSON.stringify(listData),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
return false;
});
});
Since the sever side expects a string as argument obj as a query string I think this is what you need.
data: {
obj: JSON.stringify(frmData)
},
as an alternative using as Stephen suggested on the comments
data: {
obj: $('#addTextForm').serialize()
},
I have a problem related the ajax call request searched for it on stack overflow tried all the related help that i got but can't solve the problem. the problem is that i request to a controller from my view using this code.
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var dataJson = {"contactNumber": number};
$.ajax({
type: "POST",
url: "../contactWeb/messages",
data: JSON.stringify(dataJson),
//data: dataJson,
//contentType: "application/json",
contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>
and the controller that receives the call is
[HttpPost]
public JsonResult messages(string dataJson)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , dataJson);
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
but it passes NULL value to the controller
There are couple of issues need to be fixed
whats the need of
JsonRequestBehavior.AllowGet
when your action type is post.
If you are using asp.net mvc4 use Url.Action to specify url i.e
url:"#Url.Action("ActionName","ControllerName")"
Now Talking about your issue.
Your parameter names must match, change dataJson to contactNumber.Though its ok to use there isnt any need to use JSON.stringify as you are passing single string parameter.
[HttpPost]
public JsonResult messages(string contactNumber)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
Hi could you change the name of your parameters string dataJson in your action to contactNumber in respect to the object you pass via your Ajax call
[HttpPost]
public JsonResult messages(string contactNumber) //here
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , contactNumber); //and here
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
If you want to get JSON in messages() try this:
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var data = {"contactNumber": number};
var dataJson = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../contactWeb/messages",
dataType: 'text',
data: "dataJson=" + dataJson,
//data: dataJson,
//contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>
I am sending json list from my controller:
public ActionResult LoadTree()
{
List<ListItem> list = new List<ListItem>() {
new ListItem() { Text = "Keyvan Nayyeri" },
new ListItem() { Text = "Simone Chiaretta" },
new ListItem() { Text = "Scott Guthrie" },
new ListItem() { Text = "Scott Hanselman" },
new ListItem() { Text = "Phil Haack" },
new ListItem() { Text = "Rob Conery" }
};
return new JsonResult { Data = list };
}
Trying to get the list in my view using:
var text =
$.ajax({
url: '/CourseCases/LoadTree',
dataType: 'json',
data: { },
cache: false,
type: 'GET',
success: function (data) {
}
});
alert(text);
I just get [object object]. How I can get the actual value of the object? Thanks in advance.
First you have to set the JsonRequestBehavior = JsonRequestBehavior.AllowGet in the JsonResult.
public ActionResult LoadTree()
{
List<ListItem> list = new List<ListItem>() {
new ListItem() { Text = "Keyvan Nayyeri" },
new ListItem() { Text = "Simone Chiaretta" },
new ListItem() { Text = "Scott Guthrie" },
new ListItem() { Text = "Scott Hanselman" },
new ListItem() { Text = "Phil Haack" },
new ListItem() { Text = "Rob Conery" }
};
return new JsonResult { Data = list, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
<script type="text/javascript">
$.ajax({
url: '/Home/LoadTree',
dataType: 'json',
data: {},
cache: false,
type: 'GET',
success: function (data) {
alert(data.length); // 6
// do whatever with the data
}
});
</script>
in success function you have to parse json to get actual data e.g.
var jsObject = JSON.parse(data);
and then access each item like jsObject.List[0].Text etc
Simple problem here. In your controller, you're actually assigning the list to a variable named Data inside the response data collection. Just because your success function takes a data parameter doesn't mean that the Data value you set in your controller automagically will become the data variable.
As your Data list is inside the data object: you need to do:
data.Data
inside your success function. Try this:
success: function(data) {
alert(data.Data.length);
}
function $.ajax() does not return value from server, so var text = $.ajax() will not work. You need to look at success handler instead
success: function (data) {
// data is the result of your ajax request
}
I strongly recommend you to read more at jQuery.Ajax
success(data, textStatus, jqXHR) A function to be
called if the request succeeds. The function gets passed three
arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn. This is an Ajax Event.