I have some JS which is passing (or trying to pass) a model and a string to an MVC controller.
The JS code is:
$.ajax({
url: self.ajaxValidationUrl,
type: "POST",
data: { model: $("form").serialize(), stepList: thisStepList },
async: false,
success: function(errors) {
console.log("Errors...");
if (errors.length > 0) {
anyServerError = true;
}
for (var i = 0; i < errors.length; i++) {
console.log(errors[i].ErrorMessage);
self.errorList += "<li>" + errors[i].ErrorMessage + "</li>";
}
}
});
The Controller looks like this:
[HttpPost]
public ActionResult ValidateReport(MyTemplate model, string stepList)
{
var errors = model.Validate();
return Json(errors);
}
The model parameter is blank and isn't resolving to the MyTemplate object. The post parameters are coming in ok.
I have a JSONmodel binder I got from somewhere, the place has escaped me but look at this.
public class FromJsonAttribute : CustomModelBinderAttribute
{
private readonly static JavaScriptSerializer serializer = new JavaScriptSerializer();
public override IModelBinder GetBinder()
{
return new JsonModelBinder();
}
private class JsonModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
if (string.IsNullOrEmpty(stringified))
return null;
return serializer.Deserialize(stringified, bindingContext.ModelType);
}
}
}
That allows you to do this in your controller.
[HttpPost]
public ActionResult GiftsCOG([FromJson] List<GiftModel> gifts, [FromJson] string guid)
{
}
This allows you to pass JSON from javascript.
Related
The basic problem is this. I'm using CKEditor for an interface for a blog post of sorts. CKEditor gets the wordcount, but I have to use some client-side JavaScript to clean it up. I want to pass the wordcount into the database so I know how many words each post has.
I have a viewmodel for the post:
public class NewStoryViewModel
{
[Required]
public string Title { get; set; }
[Required]
public string Content { get; set; }
[Required]
public int Genre { get; set; }
public IEnumerable<Genre> Genres { get; set; }
[Required]
public int StoryType { get; set; }
public IEnumerable<StoryType> StoryTypes { get; set; }
public int WordCount { get; set; }
[Required]
public int StoryAgeRange { get; set; }
public IEnumerable<StoryAgeRange> StoryAgeRanges { get; set; }
[Required]
public int Visibility { get; set; }
public IEnumerable<Visibility> Visibilities { get; set; }
}
And the controller for the post:
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult New (NewStoryViewModel viewModel)
{
//confirm form data is valid
if (ModelState.IsValid)
{
//create new story object
var newStory = new Story
{
AuthorId = User.Identity.GetUserId(),
Title = viewModel.Title,
Content = viewModel.Content,
GenreId = viewModel.Genre,
StoryTypeId = viewModel.StoryType,
StoryAgeRangeId = viewModel.StoryAgeRange,
VisibilityId = viewModel.Visibility,
CreatedAt = DateTime.Now,
WordCount = viewModel.WordCount
};
//add new story to db
dbContext.Stories.Add(newStory);
//save db
dbContext.SaveChanges();
return RedirectToAction("Index", "Story");
}
else
{
return View(viewModel);
}
}
On the client-side in the razor view, I have this:
$(document).ready(function () {
$('#addStoryBtn').on('click', function () {
//get the content of the div
var wordcount = $('#cke_wordcount_Content').html();
//chop off the words before the number in the string
var slicedWordCount = wordcount.slice(6);
//remove any excess white space
var trimmedWordCount = slicedWordCount.trim();
//capture the index of the slash
var indexOfSlash = trimmedWordCount.indexOf("/");
//split the string at the slash to get the words used out of the total allotted
var finalWordCount = trimmedWordCount.slice(0, indexOfSlash);
//$.ajax({
// url: "/story/new",
// type: 'POST',
// data: {
// WordCount = finalWordCount
// },
// success: function (data) {
// console.log("Success")
// },
// error: function (error) {
// console.log("error is " + error);
// }
//})
});
});
I do this because CKEditor prints the word count out of the maximum like this:
Words: 4/5000
so I use a bit of JS to remove everything I don't need and keep the number before the slash.
But the ajax post didn't work (stepping through the controller, it returns 0).
I thought about using a hiddenfield in the view. Something like:
#Html.Hidden(new { WordCount = finalWordCount })
But the razor view gives me an error that finalWordCount doesn't mean anything in the current context. I surmise it's because finalWordCount is subject to the button click and since the addPost button hasn't been clicked, finalWordCount is undefined.
Any suggestions on how to pass the wordcount to the viewmodel?
You've mentioned in the comments that you're experiencing a 500 internal server error, which I'm guessing is after you've tried Shyju's suggestion to fix the invalid JSON. My guess is you're unable to even debug the controller action right now because it's expecting an anti-forgery token to be passed to it, but you're not sending that in the body of the POST request.
To fix that, try this:
var form = // selector for your form
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
url: "/story/new",
type: 'POST',
data: {
__RequestVerificationToken: token,
WordCount: finalWordCount
},
success: function (data) {
console.log("Success")
},
error: function (error) {
console.log("error is " + error);
}
});
That should hopefully fix the validation error, allowing you to at least reach the action.
The MVC application is probably expecting a json format request body, as
that is the default configuration of asp.net MVC.
So before posting the data to the server you need to stringify the model to a proper json.
Try it like this
var data = JSON.stringify({WordCount: finalWordCount});
$.ajax({
url: "/story/new",
type: 'POST',
data: data,
success: function (data) {
console.log("Success")
},
error: function (error) {
console.log("error is " + error);
}
})
This is my model class:
public class SearchForFlight
{
public SearchForFlight()
{
Segments = new otherType();
}
public int AdultCount { get; set; }
public JourneyType JourneyType { get; set; }
public string Sources { get; set; }
public otherType Segments { get; set; }
}
public class otherType
{
public string Origin { get; set; }
public string Destination { get; set; }
public FlightCabinClass FlightCabinClass { get; set;}
public DateTime PreferredDepartureTime { get; set;
public DateTime PreferredArrivalTime { get; set; }
}
Now, My requirement is to post objects along with nested object to an external api.
The required form is something like this:
{
AdultCount: $("#AdultCount").val(),
JourneyType: $("#JourneyType :selected").text(),
PreferredAirlines: null,
Segments: [
{
Origin: $("#Origin").val(),
Destination: $("#Destination").val(),
FlightCabinClass: $("#FlightCabinClass").val(),
PreferredDepartureTime:$("#PreferredDepartureTime").val(),
PreferredArrivalTime: $("#PreferredArrivalTime").val(),
}
]
}
So, i have created another class OtherType and put all those nested objects into it.
I got the idea from this so question
How to send nested json object to mvc controller using ajax
Now, this is my Script tag with all the code inside to post simple objects along with nested objects.But nested objects value comes out to be null.
How should i model this code here.
<script>
$(document).ready(function () {
$("#btnPost").click(function () {
var sof = {
AdultCount: $("#AdultCount").val(),
JourneyType: $("#JourneyType :selected").text(),
PreferredAirlines: null,
Segments: [
{
Origin: $("#Origin").val(),
Destination: $("#Destination").val(),
FlightCabinClass: $("#FlightCabinClass").val(),
PreferredDepartureTime: $("#PreferredDepartureTime").val(),
PreferredArrivalTime: $("#PreferredArrivalTime").val(),
}
],
};
$.ajax(
{
url: "/api/Flight/SearchFlight",
type: "Post",
data: sof,
success: function (data) {
alert(data);
}
});
});
});
</script>
Posted Properties values for Origin, Destination comes out to be null.
The textbox rendered on view page are something like this:
#Html.TextBoxFor(model => model.Segments.Origin)
Any hint please.
Remove the array [] for Segments. Use contentType and stringify in your $.ajax func. Use the generated id for the Origin. It might not be "Origin". So,pls change it accordingly.
<script>
$(document).ready(function () {
$("#btnPost").click(function () {
var sof = {
AdultCount: $("#AdultCount").val(),
JourneyType: $("#JourneyType :selected").text(),
PreferredAirlines: null,
Segments: {
Origin: $("#Origin").val(),
Destination: $("#Destination").val(),
FlightCabinClass: $("#FlightCabinClass").val(),
PreferredDepartureTime: $("#PreferredDepartureTime").val(),
PreferredArrivalTime: $("#PreferredArrivalTime").val(),
},
};
$.ajax(
{
url: "/api/Flight/SearchFlight",
type: "Post",
contentType: 'application/json',
data: JSON.stringify(sof),
success: function (data) {
alert(data);
}
});
});
});
</script>
My JavascriptCode
//insert the employee and department record
this.insertEmployeeDepartment = function (Employee) {
var request = $http({
method: "post",
url: "/Employee/InsertEmployeeDepartment",
contentType: "application/json",
data: JSON.stringify(Employee)
});
return request;
}
EmployeesAPIController.cs
using System.Web.Http;
namespace EmployeeService
{
[RoutePrefix("Employee")]
public class EmployeesAPIController : ApiController
{
[HttpPost]
[Route("InsertEmployeeDepartment")]
public EmployeeDepartment InsertEmployeeAndDepartment([FromBody]EmployeeDepartment emp)
{
var xx = emp;
}
}
}
EmployeeDepartment.cs
using System.Collections.Generic;
namespace Test
{
public class EmployeeDepartment
{
public IEnumerable<Employee> Employees { get; set; }
public IEnumerable<Department> Departments { get; set; }
}
}
Models -
Employee.cs
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public int Age { get; set; }
public int Salary { get; set; }
public int DepartmentId { get; set; }
}
Department.cs
public class Department
{
public int Deptid { get; set; }
public string Deptname { get; set; }
}
The array that I am passing from Javascript is as under
In the controller method, the value is coming as null?
What wrong I am making?
Given your Javascript Object array (and not sure if it is limited to just two entries), we can re-write your javascript post model to mimic your WebApi request model.
Something like (remeber limited to 2 objects in the javascript array).
this.insertEmployeeDepartment = function (Employee) {
//construct a new object to match the WebApi Object
var dto = {
Employees: [Employee[0]], //Employee[0] is the employee record
Departments: [Employee[1]] //Employee[1] is the department record
};
var request = $http({
method: "post",
url: "/Employee/InsertEmployeeDepartment",
contentType: "application/json",
data: JSON.stringify(dto)
});
return request;
}
Now if your JavaScript array is constructed differently per method you will have to format your new model data object differently.
Edit:
To make it match exactly as i see your WebApi DepartmentId property is not on the Employee[0] record we can copy it over manually. Such as.
this.insertEmployeeDepartment = function (Employee) {
//construct a new object to match the WebApi Object
Employee[0]['DepartmentId'] = Employee[1].Deptid;
var dto = {
Employees: [Employee[0]], //Employee[0] is the employee record
Departments: [Employee[1]] //Employee[1] is the department record
};
var request = $http({
method: "post",
url: "/Employee/InsertEmployeeDepartment",
contentType: "application/json",
data: JSON.stringify(dto)
});
return request;
}
Your javascript object is an array that essentially contains a object of each type. You need to use an object that contains an array of objects of each type.
So what you have is something like
[{Age:"23", EmployeeId:"67", EmployeeName:"TestEmpName", Salary:"6666"}, {Deptid:"34", Deptname:"New Dept"}]
What you need is something like
{Employees: [{Age:23, EmployeeId:67, EmployeeName:"TestEmpName", Salary:6666, DepartmentId:0 }],
Departments: [{Deptid:34, Deptname:"New Dept"}]}
How can I pass JsonResult object from javascript function in View to Controller Action without Ajax call - just javascript - window.location.href = url?
I get JsonResult object from Controller Action to javascript function via Ajax call. Then I want to pass this object back to other Controller Action but I get object with null reference properties.
My javascript function in View:
function order(model) {
$('#details-container').html("<h2>Loading Complete Frame Module. Please wait...</h2>");
$.p({
url: '#Url.Action("CompleteFrameBrandDetails", "PacCompleteFrame")',
data: { item: model },
success: function (xml) {
if (xml.Success) {
$.p({
url: '#Url.Action("GlassCompleteFrame", "PacModule")',
data: JSON.stringify({ b2bXml: xml.Data }),
success: function (model) {
var pacModuleModel = {
Mode: model.Data.Mode,
IframeUrl: model.Data.IframeUrl.toString(),
CustomerNumber: model.Data.CustomerNumber.toString(),
ReadOnly: model.Data.ReadOnly,
GlassXml: model.Data.GlassXml.toString(),
Price: parseFloat(model.Data.Price),
Comission: model.Data.Comission.toString(),
Permissions: null,
Language: model.Data.Language.toString()
};
// here are all values in model.Data correct
// but then I can't figure out how to pass it to Controller Action without Ajax call - just with javascript command
var url = '#Url.Action("GlassCompleteFrameView", "PacModule", "__view__")';
window.location.href = url.replace("__view__", model.Data); //pacModuleModel
}
});
} else {
$.alert({
message: 'error while trying to load xml details'
});
}
}
});
}
My Controller Action:
public ActionResult GlassCompleteFrameView(PacModuleModel model)
{
// here I get object module but
// model.CustomerNumber = null
// model.GlasXml = null
// model.Price = null
// ...
return View("Glass", model);
}
I have also Model like this for automatic Json binding but dont work:
public enum ModuleMode
{
ByProduct,
ByRecipe
}
public partial class PacModuleModel
{
private PacPermissionModel permissionModel;
public ModuleMode Mode { get; set; }
public string IframeUrl { get; set; }
public string CustomerNumber { get; set; }
public bool ReadOnly { get; set; }
public string GlassXml { get; set; }
public double? Price { get; set; }
public string Comission { get; set; }
public PacPermissionModel Permissions
{
get
{
if (permissionModel == null)
{
permissionModel = new PacPermissionModel();
}
return permissionModel;
}
}
public string Language { get; set; }
}
Try this in controller
public JsonResult GlassCompleteFrameView(PacModuleModel model)
{
// here I get object module but
// model.CustomerNumber = null
// model.GlasXml = null
// model.Price = null
// ...
return Json(model, JsonRequestBehavior.AllowGet);
}
The problem was in model. It was more than 45000 char long. Now I use Session variable to get model in GlassCompleteFrameView(PacModuleModel model) and works perfect.
public ActionResult GlassCompleteFrameView(PacModuleModel model)
{
model = Session["xml"] as PacModuleModel;
return View("Glass", model);
}
I am trying to send an object array to my controller but having some difficulties.
It is sending the array and when delivered to the controller, the object count of the array also seems OK.
But if you will look inside the objects all the attributes of the objects are null
How it can be possible?
JavaScript:
function callme(results) {
for (var i = 0; i < results.length; i++) {
var endRes = {
Id: results[i].id,
Icon: results[i].icon
};
jsonObj.push(endRes);
}
sendPackage(jsonObj);
}
function sendPackage(jsonObj) {
$.ajax({
type: "POST",
url: '../../Home/RegisterList',
data: { List: jsonObj },
cache: false,
dataType: "json",
error: function (x, e, data) {
alert(data);
}
});
}
Controller:
[HttpPost]
public JsonResult RegisterList(ICollection<DetailsModel> List)
{
foreach (var i in List) ....... // other process will be here
............................... // other process will be here
return Json(new { message = "OK" });
}
Model:
public class DetailsModel
{
public string Id { get; set; }
public string Icon { get; set; }
}
Ok I've solved the problem last night by using Newton's JSON.NET (you can get it from NuGet). I've stringified the array and recieved it as a string with the controller. Finally I used json.net to convert(deserialize) this string into a collection.
To stringify: use same code but change the data section of the json request with:
data: { List : JSON.stringify(jsonObj) }
Finally recieve it by:
using Newtonsoft.Json;
public JsonResult RegisterList(string List)
{
ICollection<DetailsModel> jsonModel = JsonConvert.DeserializeObject<ICollection<DetailsModel>>(List);
}
And voila; you have a collection named jsonModel!
Unfortunately model binding of lists is not that nice and obvious in MVC. See:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
Passing the list this way works:
data: {"List[0].Id":"1", "List[0].Icon":"test"}