Reputation: 3661
I have a simple MVC model called Invitation
, it looks like this:
public class Invitation
{
public string InvitedUserDisplayName { get; set; }
public string InvitedUserEmailAddress { get; set; }
}
I want to create an user interface in the View
, using knockout.js. Where the user can input value for the 2 fields, as well as press a button that sends the invite (calling an invitation method inside my Controller, passing the Invitation
Object the user just specified.
I cannot find any solid documentation for beginners that explains this basic process. What I have so far is kind of a mess:
@Model = ViewModel.Invitation
<script src="~/lib/knockout/dist/knockout.js"></script>
@model Invitation
<form asp-controller="Home" asp-action="SendInvite" method="post">
Email: <input asp-for="InvitedUserEmailAddress" data-bind="value: invitedUserDisplayName"/> <br />
Display Name: <input asp-for="InvitedUserDisplayName" data-bind="value: invitedUserEmailAddress"/> <br />
<button data-bind="click: sendInvitation">Send Invite</button>
</form>
<script type="text/javascript">
var viewModel = {
invitedUserDisplayName: @Model.InvitedUserDisplayName,
invitedUserEmailAddress @Model.InvitedUserEmailAddress
this.sendInvitation = function () {
//call controller action, passing the newly created Invitation.
}
};
ko.applyBindings(viewModel);
</script>
Upvotes: 0
Views: 450
Reputation: 29752
I would recommend something along the lines of this (there are other ways to do this).
In your controller turn your object into JSON (I'm using the Json.Net library as it's the best), see Turn C# object into a JSON string in .NET 4 for more info
public ActionResult MyAction()
{
var viewModel;
var objectIWantToUse;
//this is a string!
viewModel.objectIWantToUseJson = JsonConvert.SerializeObject(objectIWantToUse);
return View(viewModel);
}
then in your view:
@Model = viewModel
<script src="~/lib/knockout/dist/knockout.js"></script>
<div id="someDOM" data-modeljson="@viewModel.objectIWantToUseJson">
...
Now your knockout can read the JSON using JSON.Parse, see Deserializing a JSON into a JavaScript object and get data attributes in JavaScript code:
var domElement = document.getElementById('someDOM');
var viewModelFromJson = JSON.Parse(domElement.dataset.modeljson);
ko.applyBindings(viewModelInJson);
Upvotes: 1