1
张贴背视图模型而不是模型MVC的我有以下代码:如何利用基因敲除
Index.cshtml:
@using System.Web.Script.Serialization
@model MvcApplication3.ViewModels.PersonViewModel
<script src="../../Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<!-- This is a *view* - HTML markup that defines the appearance of your UI -->
<form data-bind="submit: save">
<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody data-bind="foreach: activities">
<tr>
<td><input data-bind="value: Name" /></td>
</tr>
</tbody>
</table>
<button type="submit">Submit</button>
</form>
<script type="text/javascript">
var initialData = @Html.Raw(new JavaScriptSerializer().Serialize(Model));
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
var viewModel = {
firstName : ko.observable(initialData.Person.FirstName),
lastName : ko.observable(initialData.Person.LastName),
activities : ko.observableArray(initialData.Person.Activities),
save: function() {
$.ajax({
type: "POST",
url: "/Home/Index",
data: ko.toJSON(viewModel),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$("#resultCount").html(data);
}
});
}
}
// Activates knockout.js
ko.applyBindings(viewModel);
</script>
的HomeController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ahb.Insite.HerdRegistration.WebUI;
using MvcApplication3.Models;
using MvcApplication3.ViewModels;
namespace MvcApplication3.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var person = new Person {FirstName = "John", LastName = "Cool"};
person.Activities = new List<Activity> { new Activity { Name = "Skiing" } };
var personViewModel = new PersonViewModel (person);
return View(personViewModel);
}
[HttpPost]
public ActionResult Index(Person person)
{
//Save it
return View();
}
}
}
PersonViewModel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MvcApplication3.Models;
namespace MvcApplication3.ViewModels
{
public class PersonViewModel
{
public Person Person { get; set; }
}
}
Basica lly它做了什么是它提供了一个人的名字,姓氏和他们参与列表中的任何活动的名称的可编辑模板。
因此,该人通过personViewModel发送。
我想在此做出的改变是,不是发回一个人,而是想将该人发回到personViewModel中。
有谁知道如何更改代码以促进此?
您应该考虑使用ajax请求加载数据,而不是将其注入到视图中。也把所有的JavaScript放在一个单独的文件,谷歌不显眼的JavaScript。 – Anders 2012-08-09 11:14:46
不同意单独的ajax请求 - 这会生成实际不需要的附加请求。 – 2013-01-08 06:23:13