Pass Objects through ajax to fit Model in Controller Action in MVC 4 - ajax

I have to send data from view to Action so that I could access it as Model
My scripts:
loadData(Element);
var id = $(this).parent().closest('div').attr('id'));
$.ajax({
url: "/FormsCreation/EditLoadForm/"+ id +"?otherparameters...",
type: 'GET',
dataType: "json",
data: JSON.stringify(data),
success: function (result) {
$('#modalContent').load(result);
$('#modalDiv div[class="modal-header"]').find('h3').text('Edit DataEntry');
$('#modalFooter').attr('class', 'modal-footer hide');
$.validator.unobtrusive.parse($("#modalContent form"));
$('#modalDiv').modal({
backdrop: 'static',
keyboard: true
}, 'show');
loadDDL();
loadCheckBox();
EditbindForm(this);
}
});
function loadData(edit) {
var tds = edit.find('td');
var type = new Array();
var fieldid = new Array();
var val = new Array();
for (var i = 0; i < tds.length - 1; i++) {
var chldrn = tds.eq(i).children('input');
for (var j = 0; j < chldrn.length; j++) {
type.push(chldrn.find('[name*="field_type"]').eq(j).val());
fieldid.push(chldrn.find('[name*="field_id"]').eq(j).val());
val.push(chldrn.find('[name*="value"]').eq(j).val());
}
}
var fielddtls = {
field_id: fieldid,
field_type: type,
value: val
};
var data = {
formfields: fielddtls
};
}
I get Values from required fields and fill it into "data" and i wish to pass it to the 'GET' Action in Controller as below:
public ActionResult EditLoadForm(int formid, int id, string type, string ImageName = "None", FormsCreationModel data = null)
{
ViewBag.SubFormId = id;
var moditem = new FormsCreationModel();
if (type == "Form")
{
moditem = formRepository.GetFormValues(formid, id);
}
else
moditem = formRepository.GetTempValues(formid, ImageName);
moditem.type = type;
return View(moditem);
}
My Model
public class FormsCreationModel
{
public int form_id { get; set; }
[Display(Name="Form Name")]
public string form_name { get; set; }
public string type { get; set; }
[Display(Name="Batch No")]
public int BatchId { get; set; }
public string ImageName { get; set; }
public string UserId { get; set; }
public int SubId { get; set; }
public IList<ListFormDataModel> ListData {get;set;}
public IList<FormDetailsModel> formfields { get; set; }
public string loadType { get; set; }
}
Some Referred Links:
How to send data back to controller in MVC using knockout
How to pass multiple parameters in json format to a web service using jquery?
Post an Array of Objects via JSON to ASP.Net MVC3
Question
My Question is that whether i am doing it right? Right now I am getting "Internal Server Error 500". I want to make sure that I am in the right direction and also to know any other possibilities such using Knockout. Please guide me on this. I am Newbie towards both MVC 4 and javascripts, so need a little detailed answer rather than precise one..

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 do I populate a drop-down list with List<string> using knockout.JS

I'm playing around with knockoutJS and am struggling to get a drop-down populated with data from my model.
I'm guessing I need to convert the model data to a JSON first but for the life of me can't figure it out.
I have a basic class:
public class QuoteViewModel
{
public QuoteViewModel()
{
QuoteLines = new List<QuoteLine>();
}
public int QuoteHeaderId { get; set; }
public string QuoteNumber { get; set; }
public string Status { get; set; }
public DateTime DateCreated { get; set; }
[DisplayName("Customer")]
public SalesCustomer SelectedCustomer { get; set; }
public List<string> Customers { get; set; }
public List<QuoteLine> QuoteLines { get; set; }
}
I have an ActionMethod in a controller:
[HttpGet]
public ActionResult CreateQuote()
{
QuoteViewModel quote = new QuoteViewModel();
quote.QuoteNumber = "";
quote.Status = "P";
quote.Customers = _dbContext.SalesCustomers.Select(x => x.CustomerName).ToList();
quote.QuoteLines = new List<QuoteLine>();
return View(quote);
}
And the View():
Razor:
<select class="form-control" id="SelectedCustomer" data-bind="options: availableCustomers, optionsText: 'CustomerName', value: SelectedCustomer, optionsCaption: 'Choose...'"></select>
ViewModel:
function QuoteViewModel() {
var self = this;
self.Id = ko.observable('#Model.QuoteHeaderId');
self.QuoteNumber = ko.observable();
self.Status = ko.observable('#Model.Status');
self.DateCreated = ko.observable();
self.availableCustomers = JSON.parse('#Html.Raw(Model.Customers)');
#*$.ajax({
type: "GET",
url: '#Url.Action("GetCustomers", "Test")',
success: function (data) {
$.each(data, function (index, value) {
self.availableCustomers.push(new Customer(value));
});
},
error: function (err) {
console.log(err.responseText);
}
});*#
self.SelectedCustomer = ko.observable();
self.QuoteLines = ko.observableArray([]);
self.AddQuoteLine = function (sku, description, bomDetails) {
self.QuoteLines.push(new QuoteLineViewModel(sku, description, bomDetails));
}
self.SaveToDatabase = function () {
var dataToSend = ko.mapping.toJSON(self);
$.ajax({
type: "POST",
url: '#Url.Action("CreateQuote", "Test")',
contentType: 'application/json',
data: dataToSend,
success: function (data) {
},
error: function (err) {
console.log(err.responseText);
}
});
}
The commented out code uses ajax to get the customers and push it onto the array and that works, but is there not a way to do it directly from the model data?
Edit 1:
I don't need access to the whole SalesCustomer object, just the string name:
If I change my code as such:
Controller:
quote.Customers = _dbContext.SalesCustomers.Select(x => x.CustomerName.Trim()).ToList();
Model class property:
public List<string> Customers { get; set; }
Razor:
<select class="form-control" id="SelectedCustomer" data-bind="options: availableCustomers, value: SelectedCustomer, optionsCaption: 'Choose...'"></select>
Javascript:
self.availableCustomers = ko.observableArray([]);
var customers = '#Html.Raw(JsonConvert.SerializeObject(Model.Customers))';
self.availableCustomers = JSON.parse(customers);
self.SelectedCustomer = ko.observable();
Now the drop-down is populated with the string values of customer names. However the selected customer is not passed back to controller on POST?
Edit 2:
Well I'm not sure why its working now, but it is.
The code is the same as in Edit 1.
The only thing I can think of is I was that I erroneously had the SelectedCustomer property type still set to SalesCustomer which will obviously not work:
public SalesCustomer SelectedCustomer { get; set; }
when it should be:
public string SelectedCustomer { get; set; }
Thank you user3297291 for the assistance in pointing me in right direction.

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; }
}

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