Get json object with ajax asp.net mvc - ajax

I have a model. I used it for a while webform. But I am new on asp.net mvc. Little knowledge on this subject. I want you to help me with this. I have to get the data with ajax.Please help me.
public class BasketModel
{
public int id { get; set; }
public int name { get; set; }
public int summary { get; set; }
public int price { get; set; }
public int quantity { get; set; }
public int image { get; set; }
}
I used to my model on controller. And converted to json. and returned.
public JsonResult Test()
{
BasketModel basket = new BasketModel
{
id = 1,
name = 1,
image = 1,
price = 1,
quantity = 1,
summary = 1
};
var jsonSerializer = new JavaScriptSerializer();
var jsonbasket = jsonSerializer.Serialize(basket);
return Json(jsonbasket,JsonRequestBehavior.AllowGet);
}
I want the script object to be as follows on index.cshtml
$('.my-cart-btn').myCart({
showCheckoutModal: true,
cartItems : {
"id":1,
"name":1,
"summary":1,
"price":1,
"quantity":1,
"image":1
}
}),
I want to do this with ajax like below.
cartItems :
$.ajax({
type: 'POST',
dataType: 'json',
url: '/Product/Test',
success: function (data) {
alert(data);
} ,
data: JSON.stringify(data),
error: function(jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
}),

Looks like you are unnecessarily serializing it. The Json method is capable of sending the object as JSON back to the client.
public JsonResult Test()
{
var basket = new BasketModel
{
id = 1,
name = 1,
image = 1,
price = 1,
quantity = 1,
summary = 1
};
return Json(basket,JsonRequestBehavior.AllowGet);
}
The latest versions of MVC uses Newtonsoft Json.NET serializer behind the screen. The msdn documentation of JavaScriptSerializer also recommends to use JSON.NET
Now in your success event, you can use the JSON object as needed.
success: function (data) {
$('.my-cart-btn').myCart({
showCheckoutModal: true,
cartItems : data
});
} ,

Related

Ajax POST insert half data(some data is missed) Asp.Net MVC Ajax

I am inserting data via Ajax Post method. Data is inserted in one table but the data for secod table is not inserting. I have checked the code but I am not sure that what is mising in my code.
When I use the direct controller method then the data is inserted in both table but when I use the Ajax then data is inserted in only one table.
My Old working Controller code:
[HttpPost]
public ActionResult Create(StudentModel model)
{
if(ModelState.IsValid)
{
int id = stude.AddStudent(model);
if(id>0)
{
ModelState.Clear();
ViewBag.Success = "Data added Successfully";
}
}
return View();
}
My Ajax Controller Code:
[HttpPost]
public JsonResult Creates(StudentModel model)
{
if (ModelState.IsValid)
{
int id = stude.AddStudent(model);
if (id > 0)
{
ModelState.Clear();
ViewBag.Success = "Data added Successfully";
return Json("success", JsonRequestBehavior.AllowGet);
}
}
return Json("issue", JsonRequestBehavior.AllowGet);
}
My Model Code:
public int AddStudent(StudentModel stu)
{
student stud = new student()
{
FName = stu.FName,
LName = stu.LName,
Email = stu.Email
};
if (stu.address != null) {
stud.address= new address()
{
Details = stu.address.Details,
Country = stu.address.Country,
State = stu.address.State
};
}
using (var context = new StudentEntities())
{
context.students.Add(stud);
context.SaveChanges();
}
return stud.Id;
}
My Js/Ajax Code:
$(document).ready(function () {
//Add record
$("#add").click(function (e) {
e.preventDefault();
// var id = $();
var fname = $("#FName").val();
var lname = $("#LName").val();
var email = $("#Email").val();
var details = $("#Details").val();
var country = $("#Country").val();
var state = $("#State").val();
$.ajax({
async: true,
method: "POST",
url: '#Url.Action("Creates")',
data: JSON.stringify({
FName: fname, LName: lname, Email: email, Details: details,County: country, State: state
}),
dataType: 'JSON',
contentType: "application/json; charset=utf-8",
success: function (data) {
//window.location = data.newurl;
console.log(data);
},
error: function (err) {
alert('Failed to get data' + err);
}
});
return false;
});
});
Data is inserted in only student table and for the address table it returns null/empty and the data is skipped, although the same code will work if I remove the Ajax. But I want to use the Ajax so things will work smoothly.
Any help will be appreciated.
Update: Student Model class:
I am using N-Tire/3-Tire Architecture
My Student class Properties
public class StudentModel
{
public int Id { get; set; }
public string FName { get; set; }
public string LName { get; set; }
public string Email { get; set; }
public Nullable<int> AddressId { get; set; }
public AddressModel address { get; set; }
}
My Address Class Properties
public class AddressModel
{
public int Id { get; set; }
public string Details { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
}
There were a lot of issues in my code. I am listing it below.
The main, which I think case the problem is the Id's of my textboxes, as I am using Razor Engine and it creates the id automatic, which cause the issue, So I fix it by adding the Id and Name manually, like
#Html.EditorFor(model => model.address.Details, new { htmlAttributes = new { #class = "form-control", Name="Details", Id="Details"} })
I have changed my ajax data code to:
FName: fname, LName: lname, Email: email, address: { Details: details, Country: country, State: state }
For success message I have change Return message in my controller like:
var scess = "Data added Successfully";
return Json(new { success = true, scess }, JsonRequestBehavior.AllowGet);
and in my view I have add this line in my ajax success call:
success: function (data) {
$("#msg").text(data.scess);
console.log(data);
},
Hope this will also help other users in future.

How to send Javascript array object to the MVC5 controller method

Hi below is my question.
How to send Javascript array object to the MVC5 controller method.
The code successfully hit the action method but the list value param value is null. I tried different combination with the JSON.stringify as well.
//object class
public class MassPayoutItem
{
public string ReciverEmailID { get; set; }
public string Amount { get; set; }
public int ProviderID { get; set;}
public string AppintmentsID { get; set; }
public string TransictionID{get;set;}
public string TransictionStatus { get; set; }
public string ProviderName { get; set;}
}
//Action method
public ActionResult GetProviderMassPaymentDetail(List<MassPayoutItem> PayoutItemList){
return Json(new { Result = true, ResultData = ResaultData, Message = "" }, JsonRequestBehavior.AllowGet);
}
//JavaScript Code
function MassPay() {
alert("called MassPay");
var MassPymentList = new Array();
var objs;
$('.Include_Payment:checked').each(function () {
var ReciverEmailId = $(this).parents('tr').attr("emailid");
var appointmentids = $(this).parents('tr').attr("appointmentids");
var ProviderID = $(this).parents('tr').attr("UserId");
var Amount = $(this).parents('tr').find(".Amount").text();
var ProviderName = $(this).parents('tr').find(".OwnerName").text();
MassPymentList.push({ "ReciverEmailID": ReciverEmailId, "Amount": Amount, "ProviderID": ProviderID, "AppintmentsID": appointmentids, "ProviderName": ProviderName, "TransictionID": "abc", "TransictionStatus": "bcd" });
});
objs = JSON.stringify({ "PayoutItemList": MassPymentList });
debugger;
// _PageUrl.PayMassTransiction
// '#Url.Action("GetProviderMassPaymentDetail","Controller")'
//The call hits the method but the value is null
$.ajax({
Type: "POST"
, url: _PageUrl.PayMassTransiction
, contentType: "application/json,charset=utf-8",
traditional: true
, data: objs,
datatype: "json",
success: function (result) {
debugger;
alert("called");
}
, error: function (result) {
}
});
}
Hi Finally I solve the issue.
public class MassPayoutItem
{
public string ReciverEmailID { get; set; }
public string Amount { get; set; }
public int ProviderID { get; set;}
public string AppintmentsID { get; set; }
public string TransictionID{get;set;}
public string TransictionStatus { get; set; }
public string ProviderName { get; set;}
}
//Action method
**//This is first change i have make.**
[HttpPost, ActionName("GetProviderMassPaymentDetail")]
public ActionResult GetProviderMassPaymentDetail(List<MassPayoutItem> PayoutItemList){
return Json(new { Result = true, ResultData = ResaultData, Message = "" }, JsonRequestBehavior.AllowGet);
}
//JavaScript Code
function MassPay() {
alert("called MassPay");
var MassPymentList = new Array();
var objs;
$('.Include_Payment:checked').each(function () {
var ReciverEmailId = $(this).parents('tr').attr("emailid");
var appointmentids = $(this).parents('tr').attr("appointmentids");
var ProviderID = $(this).parents('tr').attr("UserId");
var Amount = $(this).parents('tr').find(".Amount").text();
var ProviderName = $(this).parents('tr').find(".OwnerName").text();
MassPymentList.push({ "ReciverEmailID": ReciverEmailId, "Amount": Amount, "ProviderID": ProviderID, "AppintmentsID": appointmentids, "ProviderName": ProviderName, "TransictionID": "abc", "TransictionStatus": "bcd" });
});
objs = JSON.stringify({PayoutItemList: MassPymentList });
debugger;
// _PageUrl.PayMassTransiction
// '#Url.Action("GetProviderMassPaymentDetail","Controller")'
//The call hits the method but the value is null
// below is the changed ajax calll change Type to type
$.ajax({
type: "POST"
, url: _PageUrl.PayMassTransiction
, contentType: "application/json,charset=utf-8"
,async: false
,traditional: true
, data: objs,
datatype: "json",
success: function (result) {
debugger;
alert("called");
}
, error: function (result) {
}
});
}

Post list and variable to WebApi using jQuery Ajax

I am trying to post a list of data and a variable to WebApi using jQuery Ajax.
My clientside code is:
var datatopost = new Object();
for(var i=0;i<results.length;i++)
{
datatopost["[" + i + "].NodeID"] = results[i];
}
var result;
result = grandtotal;
$.ajax({
type: "POST",
url: createurl,
dataType: "json",
traditional: true,
data: "{ 'node': '" + datatopost + "',ttl: '" + result + "'}",
statusCode: {
200: function () {
alert("success");
}
},
error:
function (res) {
alert('Error');
$("#txtmsg").val("error" + " "
+ res.status + " " + res.statusText);
}
});
My server-side code is
public HttpResponseMessage PostBuy([FromBody]List<Node> node, decimal ttl)
{
//Success code here
return new HttpResponseMessage(HttpStatusCode.OK);
}
I am receiving a bad request error in the network tab of the inspect element.
Is there any problem with my code?
I'm not completely sure, but it may be related to the "node" element in your JSON. It looks to be an object and not an array. Verify that the data is being sent properly in its JSON form.
here is my way to post a list with some other values, I post a JSON.stringify string,
var o = {};
o.UserCode = userCode;
o.Role = role;
o.UserId = r.d;
o.Hotels = [];
$('#hotel-list li :checkbox:checked').each(function () {
var ctrl = $(this);
var h = {};
h.ChainId = ctrl.val();
h.ProjectId = ctrl.next().val();
h.CityId = ctrl.next().next().val();
o.Hotels.push(h);
});
$.post("/home/UpdateDataToDb/", { d: JSON.stringify(o) }, function (r) {
alert(r.Msg);
});
and my server side code is this:
[System.Web.Mvc.HttpPost]
public JsonResult UpdateDataToDb(string d)
{
var jsonStr = d;
var json = JsonConvert.DeserializeObject<QueryPostData>(jsonStr);
//json.UserCode
//json.Role
//json.UserId
foreach (var chain in json.Hotels)
{
//My code to handle list `Hotels`
}
}
and the QueryPostData is this
public class QueryPostData
{
public string UserCode { get; set; }
public string Role { get; set; }
public string UserId { set; get; }
public List<BriefChain> Hotels { get; set; }
}
public class BriefChain
{
public string ChainId { get; set; }
public string ProjectId { get; set; }
public string CityId { get; set; }
}

Passing JSON object to Controller but loose model binding

I am trying to pass a simple JSON object to a controller using MVC3 and JSON. The object gets passed but I loose all the properties. I see all the properties in firebug on the request but am not sure why I am loosing them on the server. Do all the properties of the object need to be set in order for the mapping to work? I am using MVC3 so the binding should be build in. What am I missing?
Class:
[Serializable]
public class StoryNote
{
public int Id { get; set; }
public string Note { get; set; }
public Nullable<int> StoryCardId { get; set; }
public string CreatedBy { get; set; }
public Nullable<System.DateTime> CreateDate { get; set; }
public virtual StoryCard StoryCard { get; set; }
}
JSON:
$(document).ready(function () {
$('#newNote').click(function (e) {
e.preventDefault();
var storynote = {
StoryNote: {
Note: $('#Note').val(),
StoryCardId: $('#StoryCard_Id').val(),
CreatedBy: 'Xyz', }
};
$.ajax({
url: '#Url.Action("PostNote")',
type: 'POST',
data: JSON.stringify(storynote),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#previousNotes').append(data.Note + '<br/>' + data.CreatedBy + '<br/><hr/>');
},
});
});
});
Controller:
[HttpPost]
public JsonResult PostNote(StoryNote newStoryNote)
{
StoryNote newNote = new StoryNote { Note = newStoryNote.Note, CreatedBy = newStoryNote.CreatedBy, StoryCardId = newStoryNote.StoryCardId, CreateDate = DateTime.Now };
db.StoryNotes.Add(newStoryNote);
return Json(newStoryNote, JsonRequestBehavior.AllowGet);
}
You have a name mismatch in your code - parameter is named "StoryNote" in Javascript code and "newStoryNote" in Controller. Those names should be equal. I believe if you change
var storynote = {
StoryNote: {
Note: $('#Note').val(),
StoryCardId: $('#StoryCard_Id').val(),
CreatedBy: 'Xyz', }
};
to
var storynote = {
newStoryNote: {
Note: $('#Note').val(),
StoryCardId: $('#StoryCard_Id').val(),
CreatedBy: 'Xyz', }
};
then your code should work.

serialize List<SelectListItem> from View to Controller in MVC 3

I'm having issues passing my list object to my controller - using an ajax post.
in the view I have this:
try {
var id = schedule.value;
var data2 = #Html.Raw(Json.Encode(Model.SavedScheduleList));
var url = '#Url.Action("SetActiveSchedule", "Frame")';
$.post(url, { savedScheduleList: data2, signScheduleDataId: id }, function (data) {
});
}
catch (err)
{
alert(err);
}
My Controller looks like this:
[HttpPost]
public ActionResult SetActiveSchedule(List<SelectListItem> savedScheduleList, int signScheduleDataId)
{
try
{
return Json(null);
}
catch (Exception ex)
{
throw;
}
}
So when my Action is executed, my savedScheduleList contains a list object with 7 objects (which is the correct number of items I'm sending through. However each item seems to be "blank". ie, of the SelectListItem class, these are the property values for each item: Selected = false, Text = null, Value = null.
The Model class (which has been strongly typed to this view) is:
public class ScheduleModel
{
private SignSchedule activeSignSchedule = new SignSchedule();
private List<SelectListItem> savedSignScheduleList = new List<SelectListItem>();
public int SignDataId { get; set; }
public ScheduleFrameList ListFrames { get; set; }
public DateTime Start { get; set; }
public LogMessage LogMessage { get; set; }
public bool CommsLogVisible { get; set; }
public SignSchedule SignScheduleToMakeActive { get; set; }
public int ActiveSignScheduleId { get; set; }
//public List<SignSchedule> SavedSignScheduleList { get { return savedSignScheduleList; } }
public List<SelectListItem> SavedScheduleList { get { return savedSignScheduleList; } }
}
Examining data2 before the post, shows the correct data in Json format and examining the Request property within the Action I can see the correct values in the Form.AllKeys property as well as the Params property but it doesn't seem to correctly resolve it back to my parameter object of the Controller Action.
Is it possible what I'm trying to do?
Thanks
EDIT
Here's a string representation of data2 variable:
var data2 = [{"Selected":false,"Text":"9","Value":"2589"},false,"Text":"afsdfs","Value":"2585"},false,"Text":"sdfas","Value":"2588"}....]
I'm just showing 3 items here but there is in fact 7 as expected.
The easiest way to send complex objects and lists is to use a JSON request, like this:
var id = schedule.value;
var data2 = #Html.Raw(Json.Encode(Model.SavedScheduleList));
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ savedScheduleList: data2, signScheduleDataId: id }),
traditional: true,
success: function(result) {
// TODO: do something with the results
}
});
Note that the JSON.stringify function is natively built into modern browsers. But if you need to support legacy browsers you could include the json2.js script into your page.

Resources