knockoutjs mapping from/to POCO object - asp.net-mvc

Is there a way to map from/to a POCO and knockoutjs observable?
I have a Note class:
public class Note
{
public int ID { get; set; }
public string Date { get; set; }
public string Content { get; set; }
public string Category { get; set; }
public string Background { get; set; }
public string Color { get; set; }
}
and this is my javascript:
$(function () {
ko.applyBindings(new viewModel());
});
function note(date, content, category, color, background) {
this.date = date;
this.content = content;
this.category = category;
this.color = color;
this.background = background;
}
function viewModel () {
this.notes = ko.observableArray([]);
this.newNoteContent = ko.observable();
this.save = function (note) {
$.ajax({
url: '#Url.Action("AddNote")',
data: ko.toJSON({ nota: note }),
type: "post",
contentType: "json",
success: function(result) { }
});
}
var self = this;
$.ajax({
url: '#Url.Action("GetNotes")',
type: "get",
contentType: "json",
async: false,
success: function (data) {
var mappedNotes = $.map(data, function (item) {
return new note(item.Date, item.Content, item.Category, item.Color, item.Background);
});
self.notes(mappedNotes);
}
});
}
Ignore the fact that the save function is not used (to simplify the code here).
So, when I load the page I call the server and I retrieve a list of Note objects and I map it in javascript. Notice how ID is not mapped because I dont need it in my view.
So far so good, I see the notes on screen, but how I can save the notes back to the server?
I tried to convert the note (Im saving just the new note and not the entire collection) to JSON and send it to my controller but I don't know how to access to the note in the controller. I tried:
public string AddNote(string date, string content, string category, string background, string color)
{
// TODO
}
but is not working. I want to have something like:
public string AddNote(Note note) {}
(Btw, what's the best return for a method that just save data on DB? void?)
So, How I do this? I tried knockout.mapping plugin but it is quite confusing and I don't get it working for me.
Thank you.

ASP.NET MVC's model binder will look for properties that are case-sensitive. You need to pass your JSON object back to the server with the property names matching your poco object.
I usually do 1 of 2 things:
Make my javascript object property names capital (that way in JS, I know that this object will at some point be a DTO for the server)
function Note(date, content, category, color, background) {
this.Date = date;
this.Content = content;
this.Category = category;
this.Color = color;
this.Background = background;
};
In my AJAX call i will just create an anonymous object to pass back to the server (note this does not require ko.toJSON):
$.ajax({
url: '#Url.Action("AddNote")',
data: JSON.stringify({ note: {
Date: note.date,
Content: note.content,
Category: note.category,
Color: note.color,
Background: note.background
}
}),
type: "post",
contentType: "application/json; charset=utf-8",
success: function(result) { }
});
(note the different contentType parameter as well)
You will want to make your ActionMethod take in a (Note note) and not just the array of parameters.
Also, because the modelbinders look through the posted values in a couple different ways. I've had luck posting JSON objects with out specifying the ActionMethod parameter name:
instead of:
{ note: {
Date: note.date,
Content: note.content,
Category: note.category,
Color: note.color,
Background: note.background
}
}
just do:
{
Date: note.date,
Content: note.content,
Category: note.category,
Color: note.color,
Background: note.background
}
(but this can get dicey with arrays binding to collections and complex types...etc)
As far as the 'Best' signature for a return on a method that does a db call, we generally prefer to see boolean, but that also depends on your needs. Obviously if it is trivial data, void will be fine, but if its a bit more critical, you may want to relay a boolean (at the least) to let your client know it might need to retry (especially if there's a concurrency exception).
If you really need to let your client know what happened in the database, you can foray into the world of custom error handling and exception catching.
Also, if you need to display very specific information back to your user depending upon a successful/unsuccessful database commit, then you could look at creating custom ActionResults that redirect to certain views based upon what happened in the database transaction.
Lastly, as far as getting data back from the server and using Knockout...
again the mapping plugin will work if your property names are the same case or you create a slightly more explicit mapping
My own trick with my JS objects is below. The initialize function is something i created that should be reusable across all your objects as it just says "if the property names match (after being lowercased), either set them by calling the function (knockout compatible) or just assign the value.:
function Note(values){ //values are what just came back from the server
this.date;
this.content;
this.category;
this.color;
this.background;
initialize(values); //call the prototyped function at the bottom of the constructor
};
Note.prototype.initialize = function(values){
var entity = this; //so we don't get confused
var prop = '';
if (values) {
for (prop in values) {
if (values.hasOwnProperty(prop.toLowerCase()) && entity.hasOwnProperty(prop.toLowerCase())) {
//the setter should have the same name as the property on the values object
if (typeof (entity[prop]) === 'function') {
entity[prop](values[prop]); // we are assuming that the setter only takes one param like a Knockout observable()
} else {// if its not a function, then we will just set the value and overwrite whatever it was previously
entity[prop] = values[prop];
}
}
}
}
};

Related

asp .net mvc postdata always 0 in controller

I have very simple code (asp .net mvc c#) but just couldn't make it work. The companyId is always zero, while the booleans are returning correctly. My postdata is class called SomeObj with the ff properties
public bool isSomeBoolean1 { get; set; }
public bool isSomeBoolean2 { get; set; }
public bool isSomeBoolean3{ get; set; }
public int CompanyId { get; set; }
js:
var formData = formModule.createFormData(containerSelector + someContainer, false);
formData.append("companyId", $("#myCompanyId").val());
var promise = baseAjaxWithUpload('/SomeController/SomeAction', 'POST', formData).execute();
promise.done(function (operationStatus) {
if (operationStatus.isSuccess) {
}
});
The boolean properties returns correctly according to my input in form, but not CompanyId. I have tried wrapping it in JSON.stringify, made the companyId string type, put it back to int but parseInt(CompanyId) before passing. I also made the "CompanyId" to "companyId" but nothing worked.
I made sure that the formdata has value coz I typed in console formData.get("CompanyId") or formData.get("companyId") when I changed it to that spelling, both have values, but turns to zero in the controller.
I have also tried doing this:
var data = {
CompanyId: $("#myCompanyId").val(),
isSomeBoolean1 : true,
isSomeBoolean2 : true,
isSomeBoolean2: false,
}
var promise = baseAjaxWithUpload('/SomeController/SomeAction', 'POST', JSON.stringify(data) ).execute();
all booleans are passed correctly in controller just like formData, but not companyid. it always is 0;
this is my controller that uses it.
[HttpPost]
public ActionResult SomAction(SomeObj someObj )
{
}
I have also tried isolating the issue by adding a property called CompanyIdString with type string, then put hardcoded values like this formData.append("companyIdString", "test"), and tried to peek the value thru get, and it has, but that string returns null in controller. I also tried upper case spelling.
I mean I have been passing companyId all over the app, and never had a problem until now. What am I missing?
You can try to use application/x-www-form-urlencoded content type in the AJAX call:
var data = {
CompanyId: $("#myCompanyId").val(),
isSomeBoolean1 : true,
isSomeBoolean2 : true,
isSomeBoolean2: false,
}
$.ajax({
url: 'myUrl',
type: "POST",
contentType: 'application/x-www-form-urlencoded',
data: data,
success: function (result) {
console.log(result);
}
});

Designing data in $.ajax to match server side model definition

I'm running the following AJAX call.
var submission = {};
submission.input = [];
submission.input.push({ Id: "{ab684cb0-a5a4-4158-ac07-adff49c0c30f}" });
submission.input.push({ Id: "{bb684cb0-a5a4-4158-ac07-adff49c0c30f}" });
$.ajax({
url: "http://" + "localhost:49642/Controller/Action",
data: submission
});
It works as supposed to and in my controller I can see two elements. However, the Id fields is all-zeros. I'm certain I failed to match the definition of the object on the server-side but I'm to annoyed and frustrated right now to generate more suggestions how to shove the data to the service.
The data model is like this.
public class Thingy
{
public Guid Id { get; set; }
public IEnumerable<Guid> Blobb { get; set; }
}
I've tried to use different bracket types, apostrophes and such enclosing the guids on client-side. To no avail. What can I have forgotten?!
Edit
I need to clarify the structural definition of my information object. The controller is set up to receive the following.
public ActionResult SelectionStorage(IEnumerable<Stuff> stuff)
{
Session["Stuff"] = stuff;
return null;
}
The definition of the Stuff class is more complex but the following will suffice as a POC.
public class Stuff
{
public Guid Id { get; set; }
public IEnumerable<Guid> Ids { get; set; }
public Dictionary<String, decimal> Amounts { get; set; }
}
So, on the client, I'm performing the following set up of the submitted data object.
var submission = {};
var subIds = [];
subIds.push("{ab684cb0-a5a4-4158-ac07-adff49c0c30f}");
subIds.push("{bb684cb0-a5a4-4158-ac07-adff49c0c30f}");
submission.input = [];
submission.input.push({
Id: "{cb684cb0-a5a4-4158-ac07-adff49c0c30f}",
Ids: subIds,
Amounts: null
});
Note that the Amounts will differ from null but that headache I haven't even got to, yet.
Edit 2
New try - a simpler approach. In JS I send the following.
var stuff = {};
stuff.input = [];
stuff.input.push("{ab684cb0-a5a4-4158-ac07-adff49c0c30f}");
stuff.input.push("{bb684cb0-a5a4-4158-ac07-adff49c0c30f}");
$.ajax({
url: ...,
data: stuff,
type: "POST",
success: ...,
error: ...
});
On recieving end in C# I have this.
public ActionResult MyAction(List<String> input) { ... }
This gives null. I can't see why.
You should be able to simplify the jquery. With what you have here you don't need the submission. If you are sending a complex list back to the controller you need to name your variables but since you are just sending a string back you don't need to do that. Try changing your data to
var input = [];
input.push("{ab684cb0-a5a4-4158-ac07-adff49c0c30f}");
input.push("{bb684cb0-a5a4-4158-ac07-adff49c0c30f}");
then in the ajax call
data: input,
or
data: Json.stringify(input);
then on your controller
public ActionResult Action(List<String> input){...
Edit:
try changing your jquery to this:
var stuff= {};
stuff.Id = "{cb684cb0-a5a4-4158-ac07-adff49c0c30f}";
stuff.Ids= [];
stuff.Ids.push("{ab684cb0-a5a4-4158-ac07-adff49c0c30f}");
stuff.Ids.push("{bb684cb0-a5a4-4158-ac07-adff49c0c30f}");
then in your ajax have data: stuff, or data: Json.stringify(stuff),

MVC parameter from JQuery null

I am trying to implement sorting on a custom grid I am working on and having an issue with jQuery to MVC parameter binding.
I have a Jquery request like the one shown below
// Javascript
var dataobj =
{
test: 3,
sortInfo: self.sortInfo,
pagingInfo: {
TotalItems: 34, //headercontainer.attr("data-pagingInfo-TotalItems"),
ItemsPerPage: headercontainer.attr("data-pagingInfo-ItemsPerPage"),
CurrentPage: headercontainer.attr("data-pagingInfo-CurrentPage")
}
};
$.ajax({
url: self.viewModel.GenericGridHeaderModel.SortingCallbackUrl,
type: 'POST',
data: dataobj,
dataType: "json",
success: function (html) {...}
});
// C#
public PartialViewResult GenericGridSort(int test, SortInfo sortInfo, PagingInfo pagingInfo){
...
}
At the moment I have non null values in sortInfo object in Javascript and I see that the values are posted correctly however inside the action method the values are not getting bound correctly. All I see is default values for the sortInfo and pagingInfo parameters. In fact the test parameter is getting the value 3 correctly.
For clarity here is my sortInfo model
public enum SortDirection
{
None = 0,
Ascending = 1,
Descending = 2
}
public class SortInfo
{
public int FieldIndex { get; set; }
public string FeildName { get; set; }
public SortDirection SortDirection { get; set; }
}
Can anyone tell me what am I missing here ?
Thanks all !
I believe that you are not encoding the JSON payload.
You should be using either:
data: $.toJSON(dataobj),
or
data: JSON.stringify(dataobj),
Also, for contentType use:
contentType: 'application/json; charset=utf-8',
Here is more information on POSTing JSON payload to MVC
Also, in the dataType option you specify the type of the return value, in your case, it looks like the action method will be returning HTML, but you are specifying JSON.
Wow, as soon as I know that will not work. When you attempt to pass inner objects in your ajax data you must reference the inner objects properties strictly in the root of data ("innerobject.property": value)
Example:
var dataobj =
{
test: 3,
"sortInfo.property1": self.sortInfo.property1,
/* other properties */
"pagingInfo.TotalItems": 34,
//headercontainer.attr("data-pagingInfo-TotalItems"),
"pagingInfo.ItemsPerPage": headercontainer.attr("data-pagingInfo-ItemsPerPage"),
"pagingInfo.CurrentPage": headercontainer.attr("data-pagingInfo-CurrentPage")
};

Knockout simple object mapping

I have a simple MVC Model like this :
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string MobileNumber { get; set; }
public string EmailAddress { get; set; }
}
I would like to map one object of this type inside a knockout viewmodel in order to populate it:
var UserViewModel = function () {
var self = this;
self.user = ko.mapping.fromJS({});
$.getJSON("/UserManagement/CreateEmptyUser", function (data) {
ko.mapping.fromJS(data, self.user);
});
self.createUser = function (data, eventArgs) {
var user = data;
$.ajax({
type: "post",
contentType: "application/json",
data: ko.toJSON(user),
url: "#Url.Action("CreateUser")",
success: function () {
window.location = "#Url.Action("AddNew")";
}
});
};
};
The problem I am having is that I have no clue how to map any single object. I've tried using
self.user = ko.mapping.fromJS([]);
$.getJSON("/UserManagement/CreateEmptyUser", function (data) {
ko.mapping.fromJS(data,{}, self.user);
});
which is being used for arrays and trying to extract the element at index 0, the other solution I thought would work is the one in the 2nd comment block. Everything I found on google led me to mapping entire arrays, but nothing towards simple object mapping. Is there a proper way to do this? I would like to keep the model separated and not manually describe its properties in javascript.
Thanks,
Alex Barac
I think your problem is that you are using the mapping from method to instantiate your view model, which will give it no properties, so when you try to map the data after your JSON call, there are no properties on self.user to populate. Either create your user object with the properties you want on there, or else use mapping.fromJS to create your viewmodel in the first place:
self.user = { FirstName: ko.observable(''), etc... }
and leave your mapping line as it is, or
self.user;
$.getJSON("/UserManagement/CreateEmptyUser", function (data) {
self.user = ko.mapping.fromJS(data);
}
I kept working and checking this and I found the solution I wanted at the beginning. The idea is using #Paul Manzotti 's suggestion,
self.user;
$.getJSON("/UserManagement/CreateEmptyUser", function (data) {
self.user = ko.mapping.fromJS(data);
}
but replacing the self.user; with self.user={}; and
self.user = ko.mapping.fromJS(data)
with
ko.mapping.fromJS(data,{},self.user);
If using this, there is no need to manually declare every object's property in the viewmodel. Hope this will be of use to those that stumble upon the same issue.
If your viewModel in question needs to be an observable itself, then I found that use the mapping to return an observable array as the OP mentioned, and then returning the first item in that array works. This is also useful for return one object in ajax that you then wish to push onto an existing observableArray.
I have a helper function for this:
koMappingUsingArray = function (jsObject, mapping) {
var observableObjectArray = ko.observableArray();
var objectArray = new Array(jsObject);
ko.mapping.fromJS(objectArray, mapping, observableObjectArray);
return observableObjectArray()[0];
};
and then call it such as:
self.myObject = ko.observable();
$.ajax({
type: "POST",
url: "....",
data: ko.mapping.toJSON(???),
contentType: "application/json; charset=utf-8",
success: function (returnedObject) {
self.myObject (koMappingUsingArray(returnedObject));
});

How to send a model in jQuery $.ajax() post request to MVC controller method

In doing an auto-refresh using the following code, I assumed that when I do a post, the model will automatically sent to the controller:
$.ajax({
url: '<%=Url.Action("ModelPage")%>',
type: "POST",
//data: ??????
success: function(result) {
$("div#updatePane").html(result);
},
complete: function() {
$('form').onsubmit({ preventDefault: function() { } });
}
});
Every time there is a post, I need to increment the value attribute in the model:
public ActionResult Modelpage(MyModel model)
{
model.value = model.value + 1;
return PartialView("ModelPartialView", this.ViewData);
}
But the model is not passed to the controller when the page is posted with jQuery AJAX request. How can I send the model in the AJAX request?
The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.
As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.
For example, the Javascript:
var values =
{
"Name": "Chris",
"Color": "Green"
}
$.post("#Url.Action("Update")",values,function(data)
{
// do stuff;
});
The model:
public class UserModel
{
public string Name { get;set; }
public string Color { get;set; }
public IEnumerable<string> Contacts { get;set; }
}
The controller:
public ActionResult Update(UserModel model)
{
// do something with the model
return Json(new { success = true });
}
If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.
In our app, we do this with an extension method:
public static class JsonExtensions
{
public static string ToJson(this Object obj)
{
return new JavaScriptSerializer().Serialize(obj);
}
}
On the view, we use it to render the model:
<script type="javascript">
var model = <%= Model.ToJson() %>
</script>
You can then pass the model variable into your $.ajax call.
I have an MVC page that submits JSON of selected values from a group of radio buttons.
I use:
var dataArray = $.makeArray($("input[type=radio]").serializeArray());
To make an array of their names and values. Then I convert it to JSON with:
var json = $.toJSON(dataArray)
and then post it with jQuery's ajax() to the MVC controller
$.ajax({
url: "/Rounding.aspx/Round/" + $("#OfferId").val(),
type: 'POST',
dataType: 'html',
data: json,
contentType: 'application/json; charset=utf-8',
beforeSend: doSubmitBeforeSend,
complete: doSubmitComplete,
success: doSubmitSuccess});
Which sends the data across as native JSON data.
You can then capture the response stream and de-serialize it into the native C#/VB.net object and manipulate it in your controller.
To automate this process in a lovely, low maintenance way, I advise reading this entry that spells out most of native, automatic JSON de-serialization quite well.
Match your JSON object to match your model and the linked process below should automatically deserialize the data into your controller. It's works wonderfully for me.
Article on MVC JSON deserialization
This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.
I am achieving this either by a double click event on a grid row or click event on a button of some sort.
#model TestProject.Models.TestModel
<script>
function testButton_Click(){
var javaModel ={
ModelId: '#Model.TestId',
CreatedDate: '#Model.CreatedDate.ToShortDateString()',
TestDescription: '#Model.TestDescription',
//Here I am using a Kendo editor and I want to bind the text value to my javascript
//object. This may be different for you depending on what controls you use.
TestStatus: ($('#StatusTextBox'))[0].value,
TestType: '#Model.TestType'
}
//Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox
//selected value. This puzzled me due to the conversion to Json object in the Ajax call.
//By parsing the Type to an int this worked.
javaModel.TestType = parseInt(javaModel.TestType);
$.ajax({
//This is where you want to post to.
url:'#Url.Action("TestModelUpdate","TestController")',
async:true,
type:"POST",
contentType: 'application/json',
dataType:"json",
data: JSON.stringify(javaModel)
});
}
</script>
//This is your controller action on the server, and it will autobind your values
//to the newTestModel on post.
[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
TestModel.UpdateTestModel(newTestModel);
return //do some return action;
}
I think you need to explicitly pass the data attribute. One way to do this is to use the
data = $('#your-form-id').serialize();
This post may be helpful.
Post with jquery and ajax
Have a look at the doc here..
Ajax serialize
you can create a variable and send to ajax.
var m = { "Value": #Model.Value }
$.ajax({
url: '<%=Url.Action("ModelPage")%>',
type: "POST",
data: m,
success: function(result) {
$("div#updatePane").html(result);
},
complete: function() {
$('form').onsubmit({ preventDefault: function() { } });
}
});
All of model's field must bo ceated in m.
In ajax call mention-
data:MakeModel(),
use the below function to bind data to model
function MakeModel() {
var MyModel = {};
MyModel.value = $('#input element id').val() or your value;
return JSON.stringify(MyModel);
}
Attach [HttpPost] attribute to your controller action
on POST this data will get available

Resources