【发布时间】:2018-01-27 23:59:44
【问题描述】:
我正在尝试使用 Sammy 创建一个 SPA 应用程序。当我调用 #/entitycreate 链接时,我从 Home 控制器返回一个部分视图,其中包含要提交的 html 表单。部分视图如我所料,但其余部分不起作用。以下是我的问题和疑问,我将不胜感激。
- KO 绑定在局部视图中不起作用,即使我完全按照默认 SPA 项目模板中的方式进行了绑定(请参阅 home.viewmodel.js)。
- 这是最关键的:当我使用 ajax/post 将此表单提交到我的 API 时,我的模型总是返回一个空值,因此我无法通过我的 API 创建实体。我已经尝试使用 [FromBody] 并且没有,模型总是为空。
- 在某种意义上是一个普遍的问题,我是否应该在我的表单中包含 Html.AntiForgeryToken() 并在我的 API 操作中包含 [ValidateAntiForgeryToken] 属性?
局部视图:
@model namespace.SectorViewModel
<!-- ko with: sectorcreate -->
<div class="six wide column">
<div class="ui segments">
<div class="ui segment">
<h4 class="ui center aligned header">Create New Sector</h4>
</div>
<div class="ui secondary segment">
<form id="entity-create-form" class="ui form" action="#/sectorcreatepost" method="post" data-bind="submit: createEntity">
<!-- I am not sure if I should include AntiForgeryToken for WebAPI call -->
<!-- Html.AntiForgeryToken() -->
<fieldset>
<div class="field required">
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name, new { data_bind = "value: name" })
</div>
<div class="ui two buttons">
<button class="ui positive button" type="submit">Create</button>
<button class="ui button" type="button" id="operation-cancel">Cancel</button>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<!-- /ko -->
JS 视图模型:
function SectorCreateViewModel(app, dataModel) {
var self = this;
self.name = ko.observable("ko binding doesn't work");
self.createEntity = function () {
console.log("ko binding doesn't work");
}
Sammy(function () {
this.get("#sectorcreateget", function () {
$.ajax({
url: "/home/getview",
type: "get",
data: { viewName: "sectorcreate" },
success: function (view) {
$("#main").html(view);
}
});
return false;
});
this.post("#/sectorcreatepost",
function () {
$.ajax({
url: "/api/sectors",
type: "post",
data: $("#entity-create-form").serialize(),
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log(response);
},
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
}
});
return false;
});
this.get("#/yeni-sektor", function () {
this.app.runRoute("get", "#sectorcreateget");
});
});
return self;
}
app.addViewModel({
name: "SectorCreate",
bindingMemberName: "sectorcreate",
factory: SectorCreateViewModel
});
API 操作:
public HttpResponseMessage Post([FromBody]SectorViewModel model)
{
// model is always null, with or without [FromBody]
if (!ModelState.IsValid)
return Request.CreateResponse(HttpStatusCode.BadRequest);
// repository operations...
return response;
}
【问题讨论】:
标签: ajax asp.net-web-api knockout.js asp.net-mvc-partialview sammy.js