Binding DateTime to knockout view model with default JavaScriptSerializer - javascript

I've just started using knockout and I'm running into trouble with DateTime Serialization and Deserialization using the JavaScriptSerializer.
I've updated the gifts model in Steves koListEditor example from his blog to include a Modified DateTime field:
public class GiftModel
{
public string Title { get; set; }
public double Price { get; set; }
public DateTime Modified { get; set; }
}
Then I updated the Index.aspx to include the new field:
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<h1>Gift list editor</h1>
<p>You have asked for <span data-bind="text: gifts().length"> </span> gift(s)</p>
<form class="giftListEditor">
<table>
<tbody data-bind="template: { name: 'giftRowTemplate', foreach: gifts }"></tbody>
</table>
<button data-bind="click: addGift">Add Gift</button>
<button data-bind="enable: gifts().length > 0" type="submit">Submit</button>
</form>
<script type="text/html" id="giftRowTemplate">
<tr>
<td>Gift name: <input class="required" data-bind="value: Title, uniqueName: true"/></td>
<td>Price: \$ <input class="required number" data-bind="value: Price, uniqueName: true"/></td>
<td>Modified: <input class="required date" data-bind="value: Modified, uniqueName: true"/></td>
<td>Delete</td>
</tr>
</script>
<script type="text/javascript">
var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;
var viewModel = {
gifts : ko.observableArray(initialData),
addGift: function () {
this.gifts.push({ Title: "", Price: "", Modified:"" });
},
removeGift: function (gift) {
this.gifts.remove(gift);
},
save: function() {
ko.utils.postJson(location.href, { gifts: this.gifts });
}
};
ko.applyBindings(document.body, viewModel);
$("form").validate({ submitHandler: function() { viewModel.save() } });
</script> </asp:Content>
However when the JavaScriptSerializer serializes the Model
var initialData = <%= new JavaScriptSerializer().Serialize(Model) %>;
the Modified Date is coming out like this:
Also when using UK Dates I.e. 25/01/2011 the JavaScriptSerializer.Deserialize throws the following exception:
25/01/2011 is not a valid value for
DateTime.
Although i'm having 2 problems here the main question is has anyone successfully used knockout from MVC 2 and got the JavaScriptSerializer working with DateTimes? I realise I could write my own JavaScriptSerializer but I was hoping there was a ready made solution out there :)
Here's the code for the updated version of Steve Sanderson's koListEditor:
Code on my skydrive
Thanks
Dave

Well there are two options. You could do the simple fix by having a designated view model object which stores the preformated date time values as a string. This is generally what i do. I can then tryparse for the date value for validation.
The other option would be to implement a custom data binding. You can look at doing that here. This would be the more elegant approach. The nice thing about this apporach, you can then create you UI generation code on binding allowing you to add date picker to the ui in the process.

Not an elegant solution, but it works:
data-bind="value: eval('new ' + Modified.slice(1,-1)), uniqueName: true"
Eval might be a security issue here depending on the context.

Related

Using C# MVC multiple dynamic models in View

I have a View with several form that I'm using for searching and displaying the results as partial View in like SearchByNumber, SearchByVehicle, etc.
I'm trying to load view and execute search for different forms by posting link with querystring like www.example.com/Search?number=101010 from different view.
For the first form, SearchByNumber I only have one parameter, string number and i'm returning view with dynamic Model and its working like it should, but I only manage to make search for this form.
Here is my controller:
public ActionResult Index(string number)
{
return View(model: number);
}
and in the View I have:
<form id="searchbynumberform">
Search By Any Number:
<div class="input-group input-group-sm">
<input type="text" class="form-control" name="number" id="number" value="#Model">
<span class="input-group-btn">
<button class="btn btn-primary" type="button" name="numbersearch" id="numbersearch" disabled>
Search
</button>
</span>
</div>
</form>
My Question is, if anyone can help me, How to perform search let's say on the second form where I have int type and string name parameters?
Thank You in advance...
At the moment your Model is only the search string that was entered, which seems rather incomplete. It would make a lot more sense if the Model also contained the actual search results, which after all is what the user wants to see. And then you can also add the other search properties.
The MVC approach for this is to create a (View)Model class, somewhere in your project, something like this:
public class SearchModel
{
public string Number { get; set; }
public int? Type { get; set; }
public string Name { get; set; }
public List<SearchResult> SearchResults { get; set; }
}
And then use it e.g. like this:
public ActionResult Index(string number)
{
var model = new SearchModel
{
Number = number,
SearchResults = GetByNumber(number)
};
return View(model);
}
public ActionResult IndexOther(int type, int name)
{
var model = new SearchModel
{
Type = type,
Name = name,
SearchResults = GetByTypeAndName(type, name)
};
return View(model);
}
And in your Index.cshtml:
#model SearchModel
#* You can now use Model.Number, Model.Type, Model.Name and Model.SearchResults. *#

Use MVC Session to store Client-side values (e.g. filter text) between visits

In an MVC View, is there an efficient way to store client-side values for use on subsequent page visits?
Typical scenario
An Index page has a table that's getting a bit long so I add a filter (I know paging is another option) and use an input control with some JavaScript to limit the table rows without having to perform another "Get" from the server.
This works fine but, if I navigate off (say) into an edit page then return back to the Index page, the filter is clearly no longer there.
After a bit of searching I never found anything simple so I post my meagre answer below.
The View contains a form at the top of the page into which a user can type filter text (on form "Get", text is set from a session value):-
<form id="frmEdit">
#Html.AntiForgeryToken()
<div class="form-group row">
<div class="col-sm-6">
#Html.ActionLink("Create New", "Create", null, new { #class = "nav-item nav-link" })
</div>
<label for="search" class="col-sm-2 col-form-label text-right">Filter</label>
<div class="col-sm-4">
<input type="text" placeholder="Filter" class="form-control" id="search" value=#Session["SparesSectionFilter"]>
</div>
</div>
</form>
A script section contains the filtering JavaScript but also a postback to the controller
#section Scripts{
<script type="text/javascript">
// on load
PerformFilter();
// hook up events
$(function () {
$("input#search").on("keydown keyup", function () {
PerformFilter();
// post back to session for reuse
$.post('SparesSections/Session_Add', { __RequestVerificationToken: $('[name=__RequestVerificationToken]').val(), itemName: 'SparesSectionFilter', itemValue: $("#search").val() });
});
})
</script>
}
I have a custom base-class for my controller into which I've added the following actions. These are usable from any controller using this class. The Razor view loads the session value but I've included a "Get" in the controller for client-side options.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Session_Add(string itemName, string itemValue)
{
Session.Add(itemName, itemValue);
return Json(new { itemName = itemName, itemValue = itemValue }, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult Session_Get(string itemName)
{
return Json(new { itemName = itemName, itemValue = Session[itemName] ?? string.Empty }, JsonRequestBehavior.AllowGet);
}

Add Elements to Form Dynamically with JS

I have created 15 fields in my MySQL Table and would like to give the end user the option of using a form to add up to that many items. However, to keep the interface clean, I would like to only present them with maybe 2-3 Textboxes and give them a button that would allow them to add more should they need it.
I don't believe adding the textboxes to the form using Javascript would be an issue, but I am confused as to how to process it exactly once I have submitted the POST Data to the form handler. Can anyone shed some light on the best way to go about this?
If you have to use a normal POST variable containing all the form values, you should be able to do something like this:
When generating the textboxes with the server language and/or javascript, the way they are sent to the server is with their name attribute. If you provide a consistent way of naming the elements, you can "combine" things with numbers. For example, if you provide 2 textboxes every time the user clicks "Add" (one for "foo" and one for "bar"), then you can increment the number at the end to make sure they match.
<input type="text" name="foo1" /><input type="text" name="bar1" />
<input type="text" name="foo2" /><input type="text" name="bar2" />
and so on
Then on the server, you need to find every item in the POST variable that starts with "foo" and "bar"
for (item in POST) {
if (item startswith "foo") {
// Extract the number at the end, and find the related "bar"
}
}
Assuming that you are using ASP.NET MVC for web application, along with jQuery for client side framework.
Let's more assume that you have a model like this:
public class Gift
{
public string Name { get; set; }
public double Price { get; set; }
}
Your initial action and data could be like this:
public ActionResult Index()
{
var initialData = new[] {
new Gift { Name = "Tall Hat", Price = 39.95 },
new Gift { Name = "Long Cloak", Price = 120.00 },
};
return View(initialData);
}
Whereas, your view could be this:
<h2>Gift List</h2>
What do you want for your birthday?
<% using(Html.BeginForm()) { %>
<div id="editorRows">
<% foreach (var item in Model)
Html.RenderPartial("GiftEditorRow", item);
%>
</div>
<input type="submit" value="Finished" />
<% } %>
And partial view for gift editor could be this:
<div class="editorRow">
<% using(Html.BeginCollectionItem("gifts")) { %>
Item: <%= Html.TextBoxFor(x => x.Name) %>
Value: $<%= Html.TextBoxFor(x => x.Price, new { size = 4 }) %>
<% } %>
</div>
The key is "BeginCollectionItem" helper method, which is not standard in ASP.NET MVC. It will generate some keys for variable length models. I will add a link to files later.
Your Handler would be like this:
[HttpPost]
public ActionResult Index(IEnumerable<gift> gifts)
{
// To do: do whatever you want with the data
}
You get a list of gifts with this approach, filled with values in textboxes.
To add one more item, you need to send an ajax request to this view:
Hope it helps
Source: http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
Download: http://blog.codeville.net/blogfiles/2010/January/ListEditorDemo.zip

Dynamically adding items into view and posting back to controller (ASP.NET MVC 4)

I have a ASP.NET MVC 4 app with model, that contains and colection (IEnumerable<T> or IList<T>), i.e.:
class MyModel
{
public int Foo { get; set; }
public IList<Item> Bar { get; set; }
}
class Item
{
public string Baz { get; set; }
}
And I render the data in view with classic #for..., #Html.EditorFor... ad so on. Now there's a need to add on client side to add dynamically new items and then post it back to server.
I'm looking for an easy solution to handle the adding (in JavaScript), aka not manually creating all the inputs etc. Probably to get it somehow from editor template view. And to add it the way that when the form is submitted back to server the model binder will be able to properly create the IList<T> collection, aka some smart handling of inputs' names. I read a bunch of articles, but nothing that was easy and worked reliably (without magic strings like collection variable names, AJAX callbacks to server, ...).
So far this looks promising, but I'd like to rather rely on rendering (items known in advance) on server.
I'm not sure what do you mean 'collection variable names' and probably my solution is kind of magic you noticed.
My solution is based on copying existing editor for element and altering input names via Javascript.
First of all, we need to mark up our editor. This is a code of form outputs editor for collection
#for (var i = 0; i < Model.Count; i++)
{
<div class="contact-card">
#Html.LabelFor(c => Model[i].FirstName, "First Name")
#Html.TextBoxFor(c => Model[i].FirstName)
<br />
#Html.LabelFor(c => Model[i].LastName, "Last Name")
#Html.TextBoxFor(c => Model[i].LastName)
<br />
#Html.LabelFor(c => Model[i].Email, "Email")
#Html.TextBoxFor(c => Model[i].Email)
<br />
#Html.LabelFor(c => Model[i].Phone, "Phone")
#Html.TextBoxFor(c => Model[i].Phone)
<hr />
</div>
}
Our editor is placed into div with class contact-card. On rendering, ASP.NET MVC gives names like [0].FirstName, [0].LastName ... [22].FirstName, [22].LastName to inputs used as property editors. On submitting Model Binder converts this to collection of entities based both on indexes and property names.
Next we create javascript function that copies last editor and increases index in brackets by 1. On submitting it adds additional element to collection:
var lastContent = $("#contact-form .contact-card").last().clone();
$("#contact-form .contact-card").last().after(lastContent);
$("#contact-form .contact-card")
.last()
.find("input")
.each(function () {
var currentName = $(this).attr("name");
var regex = /\[([0-9])\]/;
var newName = currentName.replace(regex, '[' + (parseInt(currentName.match(regex)[1]) + 1) + ']');
$(this).val('');
$(this).attr('name', newName);
});
VOILA!! On submitting we will get one more element!
At the end I did similar stuff what STO was suggesting, but with the custom (non-linear) indices for collections suggested by Phil Haack.
This uses manual naming of elements (so I'm not binding directly to the model) and I can use custom instances (for empty element templates). I've also created some helper methods to generate me the code for the instance, so it's easier to generate code for actual instances from the model or empty ones.
I did this with help of Backbone (for file uploader) where i insert template whenever user click #addButton
View:
#using Telerik.Web.Mvc.UI
#{
ViewBag.Title = "FileUpload";
Layout = "~/Areas/Administration/Views/Shared/_AdminLayout.cshtml";
}
<div id="fileViewContainer" class="span12">
<h2>File upload</h2>
#foreach(var fol in (List<string>)ViewBag.Folders){
<span style="cursor: pointer;" class="uploadPath">#fol</span><br/>
}
#using (Html.BeginForm("FileUpload", "CentralAdmin", new { id = "FileUpload" }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<label for="file1">Path:</label>
<input type="text" style="width:400px;" name="destinacionPath" id="destinacionPath"/><br />
<div id="fileUploadContainer">
<input type="button" class="addButton" id="addUpload" value="Add file"/>
<input type="button" class="removeButton" id="removeUpload" value="Remove file"/>
</div>
<input type="submit" value="Upload" />
}
</div>
<script type="text/template" id="uploadTMP">
<p class="uploadp"><label for="file1">Filename:</label>
<input type="file" name="files" id="files"/></p>
</script>
#{
Html.Telerik().ScriptRegistrar().Scripts(c => c.Add("FileUploadInit.js"));
}
FileUploadInit.js
$(document).ready(function () {
var appInit = new AppInit;
Backbone.history.start();
});
window.FileUploadView = Backbone.View.extend({
initialize: function () {
_.bindAll(this, 'render', 'addUpload', 'removeUpload', 'selectPath');
this.render();
},
render: function () {
var tmp = _.template($("#uploadTMP").html(), {});
$('#fileUploadContainer').prepend(tmp);
return this;
},
events: {
'click .addButton': 'addUpload',
'click .removeButton': 'removeUpload',
'click .uploadPath': 'selectPath'
},
addUpload: function (event) {
this.render();
},
removeUpload: function (event) {
$($('.uploadp')[0]).remove();
},
selectPath: function (event) {
$('#destinacionPath').val($(event.target).html());
}
});
var AppInit = Backbone.Router.extend({
routes: {
"": "defaultRoute"
},
defaultRoute: function (actions) {
var fileView = new FileUploadView({ el: $("#fileViewContainer") });
}
});
In Controller you keep your code
I Hope this will help.

Knockout with MVC3: Knockout Model won't post collection data?

ANSWER:
Replacing this line:
self.identifiers.push(new Identifier(self.identifierToAdd(), self.selectedIdentifierTypeValue()));
With this line:
self.identifiers.push({ Key: self.identifierToAdd(), Value: self.selectedIdentifierTypeValue()});
The post requests is now sending the collection data correctly. However that doesn't solve the fact that the MVC action is not receiving it but this question is big enough already.
I can't seem to get the data from collection property of my model in knockout into my MVC model when posting to an action. If I alert ko.toJSON my identifiers() property from below it properly shows all the data, but when I try and submit that data via a normal postback (the action just takes the EquipmentCreateModel below), it looks like this:
Identifiers is empty and when I look at the ModelState error for Identifiers, it says that it cannot convert String to Dictionary<Guid, string>. What am I doing wrong? I thought MVC3 automatically converts JSON into objects if it can, as it did with the BuildingCode and Room properties?
Also why does my string data in the above picture have escaped quotes?
EDITS:
If I look at the post data, identifiers is shown as an empty array (identifiers: [{}]). I tried jsoning identifiers in the save method like so:
self.identifiers = ko.toJSON(self.identifiers());
This causes the request data to not be empty and look like this:
identifiers:"[{\"Value\":\"sdfsd\",\"Key\":\"4554f477-5a58-4e81-a6b9-7fc24d081def\"}]"
However, the same problem occurs when I debug the action. I also tried jsoning the entire model (as outlined in knockoutjs submit with ko.utils.postJson issue):
ko.utils.postJson($("form")[0], ko.toJSON(self));
But this gives a .NET error that says Operation is not valid due to the current state of the object. Which from looking at the request data it looks like it's being JSON-ified twice because each letter or character is it's own value in the HttpCollection and this is because .NET only allows 1000 max by default ('Operation is not valid due to the current state of the object' error during postback).
Using the $.ajax method to submit the data, everything works fine:
$.ajax({
url: location.href,
type: "POST",
data: ko.toJSON(viewModel),
datatype: "json",
contentType: "application/json charset=utf-8",
success: function (data) { alert("success"); },
error: function (data) { alert("error"); }
});
But due to other reasons I cannot use the $.ajax method for this, so I need it working in the normal post. Why can I toJSON the entire viewModel in the ajax request and it works, but in the normal postback it splits it up, and when I don't, all quotes are escaped in the sent JSON.
Here is my ViewModel:
public class EquipmentCreateModel
{
//used to populate form drop downs
public ICollection<Building> Buildings { get; set; }
public ICollection<IdentifierType> IdentifierTypes { get; set; }
[Required]
[Display(Name = "Building")]
public string BuildingCode { get; set; }
[Required]
public string Room { get; set; }
[Required]
[Range(1, 100, ErrorMessage = "You must add at least one identifier.")]
public int IdentifiersCount { get; set; } //used as a hidden field to validate the list
public string IdentifierValue { get; set; } //used only for knockout viewmodel binding
public IDictionary<Guid, string> Identifiers { get; set; }
}
Then my knock-out script/ViewModel:
<script type="text/javascript">
// Class to represent an identifier
function Identifier(value, identifierType) {
var self = this;
self.Value = ko.observable(value);
self.Key = ko.observable(identifierType);
}
// Overall viewmodel for this screen, along with initial state
function AutoclaveCreateViewModel() {
var self = this;
//MVC properties
self.BuildingCode = ko.observable();
self.room = ko.observable("55");
self.identifiers = ko.observableArray();
self.identiferTypes = #Html.Raw(Json.Encode(Model.IdentifierTypes));
self.identifiersCount = ko.observable();
//ko-only properties
self.selectedIdentifierTypeValue = ko.observable();
self.identifierToAdd = ko.observable("");
//functionality
self.addIdentifier = function() {
if ((self.identifierToAdd() != "") && (self.identifiers.indexOf(self.identifierToAdd()) < 0)) // Prevent blanks and duplicates
{
self.identifiers.push(new Identifier(self.identifierToAdd(), self.selectedIdentifierTypeValue()));
alert(ko.toJSON(self.identifiers()));
}
self.identifierToAdd(""); // Clear the text box
};
self.removeIdentifier = function (identifier) {
self.identifiers.remove(identifier);
alert(JSON.stringify(self.identifiers()));
};
self.save = function(form) {
self.identifiersCount = self.identifiers().length;
ko.utils.postJson($("form")[0], self);
};
}
var viewModel = new EquipmentCreateViewModel();
ko.applyBindings(viewModel);
$.validator.unobtrusive.parse("#equipmentCreation");
$("#equipmentCreation").data("validator").settings.submitHandler = viewModel.save;
View:
#using (Html.BeginForm("Create", "Equipment", FormMethod.Post, new { id="equipmentCreation"}))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Location</legend>
<div class="editor-label">
#Html.LabelFor(model => model.BuildingCode)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.BuildingCode, new SelectList(Model.Buildings, "BuildingCode", "BuildingName", "1091"), "-- Select a Building --", new { data_bind = "value:BuildingCode"})
#Html.ValidationMessageFor(model => model.BuildingCode)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Room)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Room, new { #class = "inline width-7", data_bind="value:room"})
#Html.ValidationMessageFor(model => model.Room)
</div>
</fieldset>
<fieldset>
<legend>Identifiers</legend>
<p>Designate any unique properties for identifying this autoclave.</p>
<div class="editor-field">
Add Identifier
#Html.DropDownList("identifiers-drop-down", new SelectList(Model.IdentifierTypes, "Id", "Name"), new { data_bind = "value:selectedIdentifierTypeValue"})
#Html.TextBox("identifier-value", null, new { #class = "inline width-15", data_bind = "value:identifierToAdd, valueUpdate: 'afterkeydown'" })
<button type="submit" class="add-button" data-bind="enable: identifierToAdd().length > 0, click: addIdentifier">Add</button>
</div>
<div class="editor-field">
<table>
<thead>
<tr>
<th>Identifier Type</th>
<th>Value</th>
<th></th>
</tr>
</thead>
<!-- ko if: identifiers().length > 0 -->
<tbody data-bind="foreach: identifiers">
<tr>
<td>
<select data-bind="options: $root.identiferTypes,
optionsText: 'Name', optionsValue: 'Id', value: Key">
</select>
</td>
<td><input type="text" data-bind="value: Value"/></td>
<td>Remove</td>
</tr>
</tbody>
<!-- /ko -->
<!-- ko if: identifiers().length < 1 -->
<tbody>
<tr>
<td colspan="3"> No identifiers added.</td>
</tr>
</tbody>
<!-- /ko -->
</table>
#Html.HiddenFor(x => x.IdentifiersCount, new { data_bind = "value:identifiers().length" })<span data-bind="text:identifiers"></span>
#Html.ValidationMessageFor(x => x.IdentifiersCount)
</div>
</fieldset>
<p>
<input type="submit" value="Create" />
</p>
}
I think I've found the issue or at least narrowed down the problem. The editable grid example uses simple js objects to represent gifts. You are using Identifier objects with sub observables. It seems that if we update the grid example to use more complex types it too breaks in the same way as your example. This is either by design or a bug.
http://jsfiddle.net/SZzVW/9/
I think the only solution is to write your own mapping function to submit the form.
Hope this helps.

Categories