I'm trying to post an array of values back to my action method, but with no luck as I'm getting a null for 'ParcelList'. Upload Files argument is being populated, just having a problem with ParcelList.
//ParcelList returning null
public ActionResult Add(AddShipmentVM model, ParcelVM[] ParcelList, HttpPostedFileBase[] UploadFiles )
{
if (ModelState.IsValid)
{
return RedirectToAction("Home", "CustomClearence");
}
return View(model);
}
ParcelVM
public class ParcelVM
{
[Required(ErrorMessageResourceType = typeof(AddShipmentVM), ErrorMessageResourceName = "RequiredValue")]
public string TrackTrace { get; set; }
[Required(ErrorMessageResourceType = typeof(AddShipmentVM), ErrorMessageResourceName = "RequiredValue")]
[RegularExpression(#"^\d{0,3}\.?(\d{3,3})*,?\d{1,2}$", ErrorMessageResourceType = typeof(AddShipmentVM), ErrorMessageResourceName = "InvalidWeight")]
public string GrossWeight { get; set; }
public decimal Parcelno { get; set; }
}
Ajax
When user clicks on finish, submit form
$(".actions a[href=#finish]").click(function () {
var form = jQuery('#addShipmentForm').serializeObject();
var parcelList = $.parseJSON(ko.toJSON(viewModel.parcelList()));
var tariffList = $.parseJSON(ko.toJSON(viewModel.tariffList()));
var dashBoardurl = '#Url.Action("Home","Shipment")'
var tariffObject = JSON.stringify({ TariffList: tariffList });
$('#uploadDocument input[type=file]')[0].files }
var UploadFiles = { UploadFiles: $('#uploadDocument input[type=file]')[0].files }
$.extend(form, { FinancialAndCustomsModel: tariffObject });
$.extend(form, { ParcelList: parcelList });
$.extend(form, UploadFiles);
$.ajax({
type: "POST",
data: form,
contentType: false,
success: function (result) {
if (result.status == "success") {
$(location).attr('href', dashBoardurl);
}
else {
//$(location).attr('href', addRequestUrl);
}
},
cache: false,
processData: false
});
});
Related
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.
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) {
}
});
}
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; }
}
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.
I want to post a form via ajax call also model will be passed into the action method, but want to get Model errors via json. How can I do this?
You could write a custom action filter:
public class HandleJsonErrors : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var modelState = (filterContext.Controller as Controller).ModelState;
if (!modelState.IsValid)
{
// if the model is not valid prepare some JSON response
// including the modelstate errors and cancel the execution
// of the action.
// TODO: This JSON could be further flattened/simplified
var errors = modelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new
{
x.Key,
x.Value.Errors
});
filterContext.Result = new JsonResult
{
Data = new { isvalid = false, errors = errors }
};
}
}
}
and then put it into action.
Model:
public class MyViewModel
{
[StringLength(10, MinimumLength = 5)]
public string Foo { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
[HandleJsonErrors]
public ActionResult Index(MyViewModel model)
{
// if you get this far the model was valid => process it
// and return some result
return Json(new { isvalid = true, success = "ok" });
}
}
and finally the request:
$.ajax({
url: '#Url.Action("Index")',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
foo: 'abc'
}),
success: function (result) {
if (!result.isvalid) {
alert(result.errors[0].Errors[0].ErrorMessage);
} else {
alert(result.success);
}
}
});
Something like this?
$.ajax({
type: "POST",
url: $('#dialogform form').attr("action"),
data: $('#dialogform form').serialize(),
success: function (data) {
if(data.Success){
log.info("Successfully saved");
window.close();
}
else {
log.error("Save failed");
alert(data.ErrorMessage);
},
error: function(data){
alert("Error");
}
});
[HttpPost]
public JsonResult SaveServiceReport(Model model)
{
try
{
//
}
catch(Exception ex)
{
return Json(new AdminResponse { Success = false, ErrorMessage = "Failed" }, JsonRequestBehavior.AllowGet);
}