I have been googling for a solution to my problem for two days without any luck. Can any stars in MVC3 .NET help?
I am trying to build an .NET MVC3 application to update images saved in an database.
Here is the action method
[HttpPost]
public ActionResult Edit(myImage img, HttpPostedFileBase imageFile)
{
//var img = (from imga in db.myImages
// where imga.imageID == id
// select imga).First();
if (ModelState.IsValid)
{
if (img != null)
{
img.imageType = imageFile.ContentType;
img.Data = new byte[imageFile.ContentLength];
imageFile.InputStream.Read(img.Data, 0, imageFile.ContentLength);
}
// save the product
UpdateModel(img);
db.SubmitChanges();
return RedirectToAction("Index");
}
else
{
// there is something wrong with the data values
return View(img);
}
}
Here is the view
#model JackLing.Models.myImage
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("Edit", "Image",FormMethod.Post, new { enctype = "multipart/form-data" })){
#Html.ValidationSummary(true)
<fieldset>
<legend>myImage</legend>
#Html.EditorForModel();
<div class="editor-label">Image</div>
<div class="editor-field">
#if (Model.Data != null)
{
<img src="#Url.Action("show", new { id = Model.imageID })" height="150" width="150" />
}
else {
#:None
}
</div>
<p>
<span>Choose a new file</span> <input type="file" name="imgFile"/>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
When I run the application it throws an error saying "Object reference not set to an instance of an object."
Any suggestions on how to fix the problems will be appriciated! By the way, the create and details method are all working. I think it has to do with data binding, but I'm not sure... I have no clue how to fix it.
Finally fixed the problem based on the advice from Eulerfx
here is the working action.
[HttpPost]
public ActionResult Edit(myImage img, HttpPostedFileBase imageFile)
{
myImage imgToSave = (from imga in db.myImages
where imga.imageID == img.imageID
select imga).First();
if (ModelState.IsValid)
{
if (img != null)
{
imgToSave.imageType = imageFile.ContentType;
var binaryReader = new BinaryReader(imageFile.InputStream);
imgToSave.Data = binaryReader.ReadBytes(imageFile.ContentLength);
binaryReader.Close();
}
TryUpdateModel(imgToSave);
db.SubmitChanges();
return RedirectToAction("Index");
}
else
{
// there is something wrong with the data values
return View(img);
}
}
The problem may be that the name of the file input field in the HTML is imgeFile and the name of the file parameter in MVC is imageFile. Ensure that the input field name and the action method parameter names match.
Related
I’m learning Blazor and was trying to put/save in a list some enum elements, only the ones that are checked. I have read loads of hints on stackoverflow and other web sites but am still unable to achieve that, I know something is missing but I’m blind for now
Let’s say I have an enum in a separate class calle Enums:
public enum Browsers
{
Chrome,
Edge,
Firefox,
Opera,
Safari,
Vivaldi
}
Here is the html part:
#page "/Sub2"
#using TestPatternBuilder.Data
<div class="col">
<div>Browsers:</div>
#foreach (var browser in Enum.GetValues<Browsers>())
{
<input class="form-check-input mx-0" type="checkbox" id="browsers" value="#browser" />
<label class="ms-1" for="browsers">#browser</label><br />
}
<button class="btn btn-secondary my-3" #onclick="AddBrowsers">Add Browsers</button>
<ul class="mt-2">
#foreach (var br in selectedBrowsers)
{
<li>#br.BrowserName</li>
}
</ul>
</div>
And the code part:
#code{
List<TestBrowser> selectedBrowsers = new List<TestBrowser>();
private void AddBrowsers()
{
foreach (Browsers item in Enum.GetValues(typeof(Browsers)))
{
selectedBrowsers.Add(new TestBrowser { BrowserName = item, isChecked = true });
}
}
}
I seem to have it all wrong, tried to bind without success, no idea where the isChecked state is missing...
[enter image description here](https://i.stack.imgur.com/R7y6a.png)
To achive this you'll need some sort of object to hold both your checked state as well as the enum value. For example:
public class SelectableBrowsers
{
public bool IsChecked { get; set; }
public Browsers Browser { get; set; }
}
Then you can generate a List of all enum values like this:
private List<SelectableBrowsers> _browsers = new List<SelectableBrowsers>();
protected override void OnInitialized()
{
foreach (var browser in Enum.GetValues<Browsers>())
{
_browsers.Add(new SelectableBrowsers
{
Browser = browser
});
}
}
Now you can output the browsers based on your generated list like this:
#foreach (var browser in _browsers)
{
<input #bind="browser.IsChecked" class="form-check-input mx-0" type="checkbox" id="browsers" />
<label class="ms-1" for="browsers">#browser.Browser</label><br />
}
Finally in your AddBrowsers you can loop every selected element like this:
private void AddBrowsers()
{
foreach (selectedBrowsers browser in _browsers.Where(x => x.IsChecked))
{
selectedBrowsers.Add(new TestBrowser { BrowserName = item.Browser, isChecked = true });
}
}
Hope this helps :)
An interesting alternative using Enum Flags:
#page "/"
<PageTitle>Index</PageTitle>
<h1>Hello, world!</h1>
Welcome to your new app.
<div>
#foreach (var browser in Enum.GetValues<Browsers>())
{
<div>
<input class="form-check-input mx-0" type="checkbox" id="browsers" value="#(isSelected(browser))" #onchange="() => AddToList(browser)" />
<label class="ms-1" for="browsers">#browser</label>
</div>
}
</div>
<div class="alert alert-info mt-2">
#foreach (var browser in Enum.GetValues<Browsers>())
{
#if (browser == (selectedBrowsers & browser))
{
<div>
#browser
</div>
}
}
</div>
#code {
private Browsers selectedBrowsers;
private bool isSelected(Browsers browser)
=> (selectedBrowsers & browser) == browser;
private Task AddToList(Browsers browser)
{
if ((selectedBrowsers & browser) == browser)
selectedBrowsers &= ~browser;
else
selectedBrowsers = selectedBrowsers | browser;
return Task.CompletedTask;
}
public enum Browsers
{
Chrome = 1,
Edge = 2,
Firefox = 4,
Opera = 8,
Safari = 16,
Vivaldi = 32
}
}
I have a Web API where my repository class is:
public class myRepository
{
public myClasses.Type[] GetAllTypes()
{
return new myClasses.Type[]
{
new myClasses.Type
{
typeId="1",
typeVal = "New"
},
new myClasses.Type
{
typeId="2",
typeVal = "Old"
}
};
}
public myClasses.Employee[] GetAllEmployees()
{
return new myClasses.Employee[]
{
new myClasses.Employee
{
empId="111111",
empFName = "Jane",
empLName="Doe"
},
new myClasses.Employee
{
empId="222222",
empFName = "John",
empLName="Doe"
}
};
}
public bool VerifyEmployeeId(string id)
{
myClasses.Employee[] emp = new myClasses.Employee[]
{
new myClasses.Employee
{
empId="111111",
empFName = "Jane",
empLName="Doe"
},
new myClasses.Employee
{
empId="222222",
empFName = "John",
empLName="Doe"
}
};
for (var i = 0; i <= emp.Length - 1; i++)
{
if (emp[i].empId == id)
return true;
}
return false;
}
}
and here is my controller:
public class myClassesController : ApiController
{
private myRepository empRepository;
public myClassesController()
{
this.empRepository = new myRepository();
}
public myClasses.Type[] GetTypes()
{
return empRepository.GetAllTypes();
}
public myClasses.Employee[] GetEmployees()
{
return empRepository.GetAllEmployees();
}
[HttpGet]
public bool VerifyEmployee(string id)
{
return empRepository.VerifyEmployeeId(string id);
}
}
Now I have created a web application where I included angularJS. Here is my html (EmployeeLogin.html)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Employee ID</title>
<script src="../../Scripts/jquery-2.2.0.min.js"></script>
<script src="../../Scripts/angular-ui/ui-bootstrap.min.js"></script>
<script src="../../Scripts/angular.js"></script>
<script src="EmployeeLoginCtrl.js"></script>
</head>
<body ng-app="myClassesApp">
<div ng-controller="myClassesController">
<form ng-submit="ValidateEmployeeId()" method="get" id="frmLogin" action="">
<input ng-model="empId" type="text" id="txtEmpId" />
<br />
<input type="submit" value="Submit" id="btnSubmit" />
<br />
<span id="lblMsg">{{EmployeeValidate}}</span>
</form>
</div>
</body>
</html>
What I want to accomplish is when the user enters their ID, I want to call myController function VerifyEmployee, pass it the ID entered by the user and output message of success or failure to the web page.
I am in need of some assistance fixing up my angular controller. here is what I got so far:
(function () {
angular.module("myClassesApp", []).controller("myClassesController", myValidateFunction);
myValidateFunction.$inject("$scope", "$http");
function myValidateFunction($scope, $http) {
$scope.ValidateEmployeeId = function () {
alert($scope.empId);
$http.get('http://localhost:49358/api/myClasses/VerifyEmployee/' + $scope.empId).
then(function (result) {
alert(result);
$scope.EmployeeValidate = result.data;
});
}
};
})();
My main question is how do I pass the id from the textbox to the angular controller?
Also how I ensure my angular function is only called when the form is submitted by the user, not when the page loads initially?
Can someone please point me in the right direction in regards to getting data from Web API and displaying it on the page?
So far the page loads, immediately displays "false" in the message label. then I enter ID and click submit and then nothing happens. ow can I ensure that angular function gets called?
So, in your UI, whatever you're data-binding to (ng-model, etc..) you have access to in Angular. In your example, you have <input ng-model="empId" type="text" id="txtEmpId" /> but I don't see a $scope.empId..Where is empId coming from then?
UI
<div ng-app ng-controller="myClassesController">
<div>Enter your User ID:</div>
<input ng-model="empId"></input>
<input type="submit" ng-click="checkUser()" value="Login"></input>
</div>
Controller
function myClassesController($scope) {
$scope.empId = '';
$scope.checkUser = function () {
// hit your api with user id
alert($scope.empId);
}
}
Here's a working example for you : JSFiddle
As said, i'm trying to insert an image in a table, where the type of the field is Varbinary.
What i've done so far :
I've a form with many fields:
#using (Html.BeginForm("InsertProduct", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>PRODUCT</legend>
<div class="editor-label">
#Html.LabelFor(model => model.PRODUCT_ID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PRODUCT_ID)
#Html.ValidationMessageFor(model => model.PRODUCT_ID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PRODUCT_NAME)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PRODUCT_NAME)
#Html.ValidationMessageFor(model => model.PRODUCT_NAME)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PRODUCT_IMAGE)
</div>
<div class="editor-field">
<input type="file" name="PRODUCT_IMAGE" id="PRODUCT_IMAGE" style="width: 100%;" />
</div>
<p>
<input type="submit" value="Create" class="btn btn-primary"/>
</p>
</fieldset>
}
And all these fields allow me to construct a PRODUCT object in my controller :
public ActionResult InsertProduct(PRODUCT ord)
{
MigrationEntities1 sent = new MigrationEntities1();
sent.PRODUCT.Add(ord);
sent.SaveChanges();
List<PRODUCT> Products = sent.PRODUCT.ToList();
return View("Products", Products);
}
But when i'm trying to upload the image (by clicking on Create button), i've the following :
entry is not a valid base64 string because it contains a character
that is not base 64
So first of all : is it the right way to deal with images and second, I think I need to do a pre-treatemant on my image to insert it : how to o that ?
Thanks !
Edit :
Thanks to answers received, seems to be good for insertion. But for displaying, I still have issues (only the "not found image" piture is displayed). I've try to do it two ways :
1.
<img src="LoadImage?id=#Model.product.PRODUCT_ID"/>
and in the controller
public Image LoadImage(int id)
{
String serviceAddress = ConfigurationManager.AppSettings["WCFADDRESS"];
DataServiceContext context = new DataServiceContext(new Uri(serviceAddress));
PRODUCT product = context.Execute<PRODUCT>(new Uri(serviceAddress + "prod_id?prod_id=" + id)).ToList().FirstOrDefault();
MemoryStream ms = new MemoryStream(product.PRODUCT_IMAGE);
Image img = Image.FromStream(ms);
return img;
}
And 2. :
#{
if (Model.product.PRODUCT_IMAGE != null)
{
WebImage wi = new WebImage(Model.product.PRODUCT_IMAGE);
wi.Resize(700, 700,true, true);
wi.Write();
}
}
But none of them are working. What am I doing wrong ?
1) Change your database table to have these columns:
1: ProductImage - varbinary(MAX)
2: ImageMimeType - varchar(50)
2) Change your action method like this:
public ActionResult InsertProduct(PRODUCT ord,
HttpPostedFileBase PRODUCT_IMAGE)
{
if (ModelState.IsValid)
{
MigrationEntities1 sent = new MigrationEntities1();
if (image != null)
{
ord.ProductImage= new byte[PRODUCT_IMAGE.ContentLength];
ord.ImageMimeType = PRODUCT_IMAGE.ContentType;
PRODUCT_IMAGE.InputStream.Read(ord.ProductImage, 0,
PRODUCT_IMAGE.ContentLength);
}
else
{
// Set the default image:
Image img = Image.FromFile(
Server.MapPath(Url.Content("~/Images/Icons/nopic.png")));
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Png); // change to other format
ms.Seek(0, SeekOrigin.Begin);
ord.ProductImage= new byte[ms.Length];
ord.ImageMimeType= "image/png";
ms.Read(ord.Pic, 0, (int)ms.Length);
}
try
{
sent.PRODUCT.Add(ord);
sent.SaveChanges();
ViewBag.HasError = "0";
ViewBag.DialogTitle = "Insert successful";
ViewBag.DialogText = "...";
}
catch
{
ViewBag.HasError = "1";
ViewBag.DialogTitle = "Server Error!";
ViewBag.DialogText = "...";
}
List<PRODUCT> Products = sent.PRODUCT.ToList();
return View("Products", Products);
}
return View(ord);
}
This action method is just for create. you need some works for edit and index too. If you have problem to doing them, tell me to add codes of them to the answer.
Update: How to show images:
One way to show stored images is as the following:
1) Add this action method to your controller:
[AllowAnonymous]
public FileContentResult GetProductPic(int id)
{
PRODUCT p = db.PRODUCTS.FirstOrDefault(n => n.ID == id);
if (p != null)
{
return File(p.ProductImage, p.ImageMimeType);
}
else
{
return null;
}
}
2) Add a <img> tag in the #foreach(...) structure of your view (or wherever you want) like this:
<img width="100" height="100" src="#Url.Action("GetProductPic", "Products", routeValues: new { id = item.ID })" />
Change the Image type on the sql sever to Byte[] and use something like this. This is how I have stored images in the past.
http://www.codeproject.com/Articles/15460/C-Image-to-Byte-Array-and-Byte-Array-to-Image-Conv
If not, you can always just store the image locally and pass the image location through a string into the SQL data base, this method works well and is quick to set up.
So, here are the modifications to do :
To insert data in the database :
[HttpPost]
public ActionResult InsertProduct(PRODUCT ord, HttpPostedFileBase image)
{
MigrationEntities1 sent = new MigrationEntities1();
if (image != null)
{
ord.PRODUCT_IMAGE = new byte[image.ContentLength];
image.InputStream.Read(ord.PRODUCT_IMAGE, 0, image.ContentLength);
}
sent.PRODUCT.Add(ord);
sent.SaveChanges();
List Products = sent.PRODUCT.ToList();
return View("Products", Products);
}
Note: this is the "light" way, for something that is more complete, have a look to Amin answer.
For displaying :
In the view
<img src="LoadImage?id=#Model.product.PRODUCT_ID"/>
And in the controller :
public FileContentResult LoadImage(int id)
{
String serviceAddress = ConfigurationManager.AppSettings["WCFADDRESS"];
DataServiceContext context = new DataServiceContext(new Uri(serviceAddress));
PRODUCT product = context.Execute<PRODUCT>(new Uri(serviceAddress + "prod_id?prod_id=" + id)).ToList().FirstOrDefault();
return new FileContentResult(product.PRODUCT_IMAGE, "image/jpeg");
}
And everything is ok now, thanks !
I have searched around for a while now with no joy. I am trying to save an image to my SQL db as a byte array, then I am trying to display it later. The display part is not working. I don't know if it's a problem with the save or the display. The save appears to be working ok, I can see 'Binary Data' in my SQL table. Any suggestions?
What's happening is that I get a broken image icon on my page. Even if I manually goto the URL e.g. .../Treatments/LoadImage/14 it's broken.
Model contains this in my table definition:
public byte[] Photo { get; set; }
Create View:
<div class="editor-label">
#Html.LabelFor(model => model.Photo)
</div>
<div class="editor-field">
<input type="file" name="photo" />
</div>
Create Controller:
[HttpPost]
public ActionResult Create([Bind(Exclude = "Photo")]Treatment treatment)
{
if (ModelState.IsValid)
{
treatment.Photo = GetByteArrayFromFile();
treatment.WebOrder = db.Treatments.Count();
db.Treatments.Add(treatment);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.TreatmentTypeId = new SelectList(db.TreatmentTypes, "Id", "Name", treatment.TreatmentTypeId);
return View(treatment);
}
private byte[] GetByteArrayFromFile() {
int fileLength = Request.Files["photo"].ContentLength;
byte[] byteArray = new byte[fileLength];
return byteArray;
}
Display View:
<div class="display-label">
#Html.DisplayNameFor(model => model.Photo)
</div>
<div class="display-field">
<img src="#Url.Action("LoadImage", new { Id = Model.Id })" />
</div>
LoadImage Controller:
public ActionResult LoadImage(int Id) {
byte[] bytes = db.Treatments.Find(Id).Photo;
return File(bytes, "image/jpeg");
}
I have added:
#using (Html.BeginForm("Create", "Treatments", FormMethod.Post, new { enctype = "multipart/form-data" })) {
// View Code Omitted
}
to my Create view.
Is there something elementary wrong with my code? Any suggestions? Thanks.
It was a problem with my GetByteArrayFromFile Method. My original method above returned an array of zeros only. Using this, I fixed my issue:
private byte[] GetByteArrayFromFile() {
WebImage image = WebImage.GetImageFromRequest();
byte[] byteArray = image.GetBytes();
return byteArray;
}
I am looking for a VERY simple example that shows wiring up Knockback code to a backbone model that connects via RESTful service. I am using ServiceStack|c# backend. All of the links below are too complicated and use localStore rather than a RESTful service via url. I also prefer to see examples in Javascript not CoffeeScript.
My example url is something like localhost/entities where hitting this will cause the RESTful webservice to return all of the entities. Hitting it with localhost/entity/1 would return the entity with an Id of 1.
_http://kmalakoff.github.com/knockback/index.html
_https://github.com/kmalakoff/knockback-reference-app/
_https://github.com/addyosmani/todomvc
The following is the example from knockback tutorial on the first link:
Models, Collection, ViewModel, and Bindings:
// Generated by CoffeeScript 1.3.3
var model, view_model;
model = new Backbone.Model({
first_name: "Planet",
last_name: "Earth"
});
view_model = kb.viewModel(model);
view_model.full_name = ko.computed((function() {
return "" + (this.first_name()) + " " + (this.last_name());
}), view_model);
ko.applyBindings(view_model, $('#kb_view_model_computed')[0]);
But there is no mention of how you would wire the backbone model up to your RESTful webservice.
There are examples of how do this via Backbone but I am uncertain as to how things change when using Knockback.
The following links were found, but not helpful:
_http://stackoverflow.com/questions/7992431/using-knockoutjs-backbone-together
_http://stackoverflow.com/questions/9704220/is-knockback-js-production-ready
_http://stackoverflow.com/questions/10434203/defining-models-on-server-side-when-using-mvvm-with-knockout-js
Thanks in advance for any assistance provided. Btw you don't want hyperlinks you get underscores... ;)
With much help and support from Kevin Malakoff from the great Knockback project I was able to get a small example working! I used the ServiceStack Backbone Todos project as a starting point.
c# file: Global.asax.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using ServiceStack.Redis;
using ServiceStack.ServiceInterface;
using ServiceStack.WebHost.Endpoints;
namespace MyApp
{
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class PersonService : RestServiceBase<Person>
{
public static Person kevin = new Person { Id = 1, FirstName = "Kevin", LastName = "Malakoff" };
public static Person scott = new Person { Id = 2, FirstName = "Scott", LastName = "Idler" };
public static List<Person> people = new List<Person> { kevin, scott };
public override object OnGet(Person person)
{
if (person.Id != default(int))
return people[person.Id-1];
return people;
}
public override object OnPost(Person person)
{
return base.OnPost(person);
}
public override object OnPut(Person person)
{
return OnPost(person);
}
public override object OnDelete(Person person)
{
return base.OnDelete(person);
}
}
public class AppHost : AppHostBase
{
public AppHost() : base("MyApp", typeof(PersonService).Assembly) { }
public override void Configure(Funq.Container container)
{
ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
Routes
.Add<Person>("/persons")
.Add<Person>("/persons/{Id}");
}
}
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
new AppHost().Init();
}
}
}
html file: default.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>MyApp2</title>
<script>window.JSON || document.write('<script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js">\x3C/script>')</script>
<script src="Scripts/jquery-1.8.0.js" type="text/javascript" ></script>
<script src="Scripts/knockback-full-stack-0.16.1.js" type="text/javascript" ></script>
<script src="myapp.js" type="text/javascript" ></script>
</head>
<body>
<div id="myapp">
<div class="title">
<h1>MyApp</h1>
</div>
<div class="content">
<div id='kb_observable'>
<p>First name: <input class='text' data-bind="value: firstName" /></p>
<p>Last name: <input class='input-small pull-right' data-bind="value: lastName" /></p>
<p>Hello, <span data-bind="text: fullName"></span>!</p>
</div>
<div id="kb_collection_observable">
<div data-bind="if: persons">
<span>Has Persons</span>
</div>
<div data-bind="foreach: persons">
<p>First name: <input class='text' data-bind="value: firstName" /></p>
<p>Last name: <input class='input-small pull-right' data-bind="value: lastName" /></p>
</div>
</div>
</div>
</div>
</body>
</html>
javascript file: myapp.js
$(function() {
//model
var PersonModel = Backbone.Model.extend({ urlRoot: '/MyApp/persons' });
var model = new PersonModel({ id: 1 });
model.fetch();
//viewmodel
var PersonViewModel = function (person) {
this.firstName = kb.observable(person, 'firstName');
this.lastName = kb.observable(person, 'lastName');
this.fullName = ko.computed((function () {
return "" + (this.firstName()) + " " + (this.lastName());
}), this);
};
var personViewModel = new PersonViewModel(model);
//binding
ko.applyBindings(personViewModel, $('#kb_observable')[0]);
//model
var PersonsModel = Backbone.Collection.extend({ model: PersonModel, url: '/MyApp/persons' });
var personsModel = new PersonsModel();
personsModel.fetch();
//viewmodel
var PersonsViewModel = function (persons) {
this.persons = kb.collectionObservable(persons)
};
var personsViewModel = new PersonsViewModel(personsModel);
//binding
ko.applyBindings(personsViewModel, $('#kb_collection_observable')[0]); });
I put together a very simple example. It assumes you already know how to use backbone and knockout so this just gives a quick example of how they can be used together
http://coder2.blogspot.com/2013/02/backbonejs-and-knockoutjs.html