Use Knockout practice 01 in ASP. net mvc to bind a Json object and knockoutjson
This article uses Knockout in ASP. net mvc and uses EF Code First to create a database. Finally, bind the Knockout to a Json object.
Create a domain model.
namespace MvcApplication3.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}
}
The context derived from DbContext.
using System.Data.Entity;
namespace MvcApplication3.Models
{
public class ProductContext : DbContext
{
public ProductContext() : base("conn")
{
Database.SetInitializer(new ProductInitializer());
}
public DbSet<Product> Products { get; set; }
}
}
Set some seed data.
using System.Data.Entity;
namespace MvcApplication3.Models
{
public class ProductInitializer : DropCreateDatabaseIfModelChanges<ProductContext>
{
protected override void Seed(ProductContext context)
{
Context. Products. Add (new Product () {Name = "", Price = 85 M, Category = "Prose "});
Context. Products. Add (new Product () {Name = "", Price = 95 M, Category = ""});
Context. Products. Add (new Product () {Name = "Spring blossom", Price = 105 M, Category = "Prose "});
}
}
}
ConnectionStrings node configuration in Web. config.
<connectionStrings>
...
<Add name = "conn" connectionString = "Data Source = .; user = username; Password = Password; Initial Catalog = ProductStore; Integrated Security = True "providerName =" System. data. sqlClient "/>
</connectionStrings>
Create an interface for the Product domain model.
using System.Collections.Generic;
namespace MvcApplication3.Models
{
public interface IProductRepository
{
IEnumerable<Product> GetAll();
Product GetById(int id);
Product Add(Product item);
bool Update(Product item);
bool Delete(int id);
}
}
The implementation of the IProductRepository interface.
using System.Data;
namespace MvcApplication3.Models
{
public class ProductRepository : IProductRepository
{
private ProductContext db = new ProductContext();
public System.Collections.Generic.IEnumerable<Product> GetAll()
{
return db.Products;
}
public Product GetById(int id)
{
return db.Products.Find(id);
}
public Product Add(Product item)
{
db.Products.Add(item);
db.SaveChanges();
return item;
}
public bool Update(Product item)
{
db.Entry(item).State = EntityState.Modified;
db.SaveChanges();
return true;
}
public bool Delete(int id)
{
Product product = db.Products.Find(id);
db.Products.Remove(product);
if (db.SaveChanges() > 0)
{
return true;
}
else
{
return false;
}
}
}
}
Provide an Action in HomeController to obtain the first Product record in the database and return it in json format.
using System;
using System.Web.Mvc;
using MvcApplication3.Models;
namespace MvcApplication3.Controllers
{
public class HomeController : Controller
{
static readonly IProductRepository repository = new ProductRepository();
public ActionResult Index()
{
return View();
}
public JsonResult GetFirstProduct()
{
var product = repository.GetById(1);
return Json(product, JsonRequestBehavior.AllowGet);
}
}
}
In Home/Index. cshtml, bind the Knockout to a json-type View Model and send an asynchronous request to the Controller to update the name attribute of the json object.
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div data-bind="text:name"></div> <input type="text" data-bind="value:name"/>
@section scripts
{
<script src="~/Scripts/knockout-2.2.0.js"></script>
<script type="text/javascript">
$(function() {
ko.applyBindings(productViewModel);
$.getJSON('@Url.Action("GetFirstProduct","Home")', function (data) {
productViewModel.name(data.Name);
});
});
var productViewModel = {
id: ko.observable(""),
Name: ko. observable ("Initial Value "),
price: ko.observable(""),
category: ko.observable("")
};
</script>
}
Above,
○ View Model is a json object.
○ Use ko. observable ("") to synchronize View Model members with the interface
○ Use the data-bind attribute in the interface View to synchronize data with the View Model
How to parse json in aspnet mvc
Public static DataTable JsonToDataTable (string strJson)
{
// Retrieve the table name
Regex rg = new Regex (@"(? <= {) [^:] + (? =: \ [) ", RegexOptions. IgnoreCase );
String strName = rg. Match (strJson). Value;
DataTable tb = null;
// Remove the table name
StrJson = strJson. Substring (strJson. IndexOf ("[") + 1 );
StrJson = strJson. Substring (0, strJson. IndexOf ("]");
// Obtain data
Rg = new Regex (@"(? <= {) [^}] + (? = })");
MatchCollection mc = rg. Matches (strJson );
For (int I = 0; I <mc. Count; I ++)
{
String strRow = mc [I]. Value;
String [] strRows = strRow. Split (',');
// Create a table
If (tb = null)
{
Tb = new DataTable ();
Tb. TableName = strName;
Foreach (string str in strRows)
{
DataColumn dc = new DataColumn ();
String [] strCell = str. Split (':');
Dc. ColumnName = strCell [0]. ToString ();
Tb. Columns. Add (dc );
}
Tb. AcceptChanges ();
}
// Add content
DataRow dr = tb. NewRow ();
For (int r = 0; r <strRows. Length; r ++)
{
... The remaining full text>
In aspnet mvc mode, how does one transmit data to the foreground using JSON?
~~ Use Js to call webservice. The implementation is a little simpler. Let him return a List <T>, and then it will become Json-type data in the foreground. Too long
Let's take a look at this: msdn.microsoft.com/...x#Y546