在MVC嵌套的ViewModels保存,可以有以下視圖模型:如何執行動態添加,刪除和在knockoutjs
public class MyCVViewModel
{
[Required]
[StringLength(100, ErrorMessage = "Resume Title cannot exceed 100 characters.")]
[Display(Name = "Resume Title")]
public string ResumeTitle { get; set; }
[Required]
[StringLength(1000, ErrorMessage = "Personal Statment cannot exceed 1000 characters.")]
[Display(Name = "Personal Statement")]
public string Statement { get; set; }
public List<MyCompanyViewModel> Companies { get; set; }
}
public class MyCompanyViewModel
{
[Required]
[StringLength(100, ErrorMessage = "Company Name cannot exceed 100 characters.")]
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Job Title cannot exceed 100 characters.")]
[Display(Name = "Job Title")]
public string JobTitle { get; set; }
[Required]
[DataType(DataType.Date)]
[Display(Name = "Start Date")]
public DateTime JobStartDate { get; set; }
[Required]
[DataType(DataType.Date)]
[Display(Name = "End Date")]
public DateTime JobEndDate { get; set; }
[Required]
[StringLength(1000, ErrorMessage = "Job Description cannot exceed 1000 characters.")]
[Display(Name = "Job Description")]
public string JobDescription { get; set; }
}
MyCVViewModel有MyCompanyViewModels的名單,這是非常簡單的。
我開始學習knockoutjs並試圖複製knockoutjs在同一個視圖模型。
這裏是我試過到目前爲止:
//company viewmodel
function Company(data) {
this.name = ko.observable(data.name);
//other stuff
}
//cv view model
function CVViewModel() {
var self = this;
self.title = ko.oberservable();
self.statement = ko.oberservalbe();
//list of company view model
self.companies = ko.observableArray();
//add company
self.addCompany = function() {
self.companies.push({
name: ""
});
};
//remove company
self.removeCompany = function (company) {
self.companies.remove(company);
};
//populate with json
$.getJSON("/Class/FillCompany", function (allData) {
var mappedTasks = $.map(allData, function (item) { return new Company(item) });
self.companies(mappedTasks);
});
};
// Activate knockout binding
ko.applyBindings(new CVViewModel());
添加和刪除工作得很好,但我不知道如何挽救整個CV視圖模型並將其張貼在asp.net的MVC控制器。
大多數教程貼在網上的孩子視圖模型(在公司我的情況列表),並將其發佈到服務器,但不是父視圖模型(在我的情況cvviewmdoel)。
所以在我看來,我只能在公司發佈到服務器:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<textarea name="companies" data-bind="value: ko.toJSON(companies)"></textarea>
<button type="submit">Save</button>
}
,並在我的控制器我希望公司的名單:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([FromJson] IEnumerable<Company> companies)
{
//save to database etc..
}
如何張貼整個父視圖模型,以便我的控制器看起來更像:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(MyCVViewModel cv)
{
//save to database etc..
}
其中MyCVViewModel包含已經有公司名單。
只需發佈主viewModel,使用ko.toJSON。如果你在服務器端有類似名稱的東西,它會奇蹟般地映射到你的服務器端對象。 – dbugger 2015-02-12 02:45:28
只是張貼這樣的'ko.toJSON(個體經營)'如果你的機型在兩端同它應該工作,歡呼聲 – 2015-02-12 07:28:52