【发布时间】:2012-04-08 04:12:58
【问题描述】:
回答: 替换这一行:
self.identifiers.push(new Identifier(self.identifierToAdd(), self.selectedIdentifierTypeValue()));
用这一行:
self.identifiers.push({ Key: self.identifierToAdd(), Value: self.selectedIdentifierTypeValue()});
发布请求现在可以正确发送集合数据。然而,这并不能解决 MVC 操作没有收到它的事实,但这个问题已经足够大了。
发布到操作时,我似乎无法从模型的集合属性中获取数据,以将数据剔除到我的 MVC 模型中。如果我从下方提醒ko.toJSON 我的identifiers() 属性,它会正确显示所有数据,但是当我尝试通过正常回发提交该数据时(该操作仅采用下面的 EquipmentCreateModel),它看起来像这样:
标识符为空,当我查看标识符的 ModelState 错误时,它显示为 cannot convert String to Dictionary<Guid, string>。我究竟做错了什么?我认为 MVC3 会自动将 JSON 转换为对象,就像它对 BuildingCode 和 Room 属性所做的那样?
还有为什么我上图中的字符串数据有转义引号?
编辑:
如果我查看发布数据,标识符显示为一个空数组 (identifiers: [{}])。我在 save 方法中尝试了 jsoning 标识符,如下所示:
self.identifiers = ko.toJSON(self.identifiers());
这会导致请求数据不为空,如下所示:
identifiers:"[{\"Value\":\"sdfsd\",\"Key\":\"4554f477-5a58-4e81-a6b9-7fc24d081def\"}]"
但是,当我调试操作时会出现同样的问题。我还尝试将整个模型 json 化(如 knockoutjs submit with ko.utils.postJson issue 中所述):
ko.utils.postJson($("form")[0], ko.toJSON(self));
但这会产生一个 .NET 错误,上面写着 Operation is not valid due to the current state of the object. 从查看请求数据来看,它似乎被 JSON 化了两次,因为每个字母或字符在 HttpCollection 中都是它自己的值,这是因为只有 .NET默认情况下最多允许 1000 个 ('Operation is not valid due to the current state of the object' error during postback)。
使用$.ajax方法提交数据,一切正常:
$.ajax({
url: location.href,
type: "POST",
data: ko.toJSON(viewModel),
datatype: "json",
contentType: "application/json charset=utf-8",
success: function (data) { alert("success"); },
error: function (data) { alert("error"); }
});
但由于其他原因,我不能为此使用 $.ajax 方法,所以我需要它在普通帖子中工作。为什么我可以 toJSON ajax 请求中的整个 viewModel 并且它可以工作,但是在正常的回发中它会拆分它,而当我不这样做时,所有引号都会在发送的 JSON 中转义。
这是我的 ViewModel:
public class EquipmentCreateModel
{
//used to populate form drop downs
public ICollection<Building> Buildings { get; set; }
public ICollection<IdentifierType> IdentifierTypes { get; set; }
[Required]
[Display(Name = "Building")]
public string BuildingCode { get; set; }
[Required]
public string Room { get; set; }
[Required]
[Range(1, 100, ErrorMessage = "You must add at least one identifier.")]
public int IdentifiersCount { get; set; } //used as a hidden field to validate the list
public string IdentifierValue { get; set; } //used only for knockout viewmodel binding
public IDictionary<Guid, string> Identifiers { get; set; }
}
然后是我的淘汰脚本/ViewModel:
<script type="text/javascript">
// Class to represent an identifier
function Identifier(value, identifierType) {
var self = this;
self.Value = ko.observable(value);
self.Key = ko.observable(identifierType);
}
// Overall viewmodel for this screen, along with initial state
function AutoclaveCreateViewModel() {
var self = this;
//MVC properties
self.BuildingCode = ko.observable();
self.room = ko.observable("55");
self.identifiers = ko.observableArray();
self.identiferTypes = @Html.Raw(Json.Encode(Model.IdentifierTypes));
self.identifiersCount = ko.observable();
//ko-only properties
self.selectedIdentifierTypeValue = ko.observable();
self.identifierToAdd = ko.observable("");
//functionality
self.addIdentifier = function() {
if ((self.identifierToAdd() != "") && (self.identifiers.indexOf(self.identifierToAdd()) < 0)) // Prevent blanks and duplicates
{
self.identifiers.push(new Identifier(self.identifierToAdd(), self.selectedIdentifierTypeValue()));
alert(ko.toJSON(self.identifiers()));
}
self.identifierToAdd(""); // Clear the text box
};
self.removeIdentifier = function (identifier) {
self.identifiers.remove(identifier);
alert(JSON.stringify(self.identifiers()));
};
self.save = function(form) {
self.identifiersCount = self.identifiers().length;
ko.utils.postJson($("form")[0], self);
};
}
var viewModel = new EquipmentCreateViewModel();
ko.applyBindings(viewModel);
$.validator.unobtrusive.parse("#equipmentCreation");
$("#equipmentCreation").data("validator").settings.submitHandler = viewModel.save;
查看:
@using (Html.BeginForm("Create", "Equipment", FormMethod.Post, new { id="equipmentCreation"}))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Location</legend>
<div class="editor-label">
@Html.LabelFor(model => model.BuildingCode)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.BuildingCode, new SelectList(Model.Buildings, "BuildingCode", "BuildingName", "1091"), "-- Select a Building --", new { data_bind = "value:BuildingCode"})
@Html.ValidationMessageFor(model => model.BuildingCode)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Room)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.Room, new { @class = "inline width-7", data_bind="value:room"})
@Html.ValidationMessageFor(model => model.Room)
</div>
</fieldset>
<fieldset>
<legend>Identifiers</legend>
<p>Designate any unique properties for identifying this autoclave.</p>
<div class="editor-field">
Add Identifier
@Html.DropDownList("identifiers-drop-down", new SelectList(Model.IdentifierTypes, "Id", "Name"), new { data_bind = "value:selectedIdentifierTypeValue"})
@Html.TextBox("identifier-value", null, new { @class = "inline width-15", data_bind = "value:identifierToAdd, valueUpdate: 'afterkeydown'" })
<button type="submit" class="add-button" data-bind="enable: identifierToAdd().length > 0, click: addIdentifier">Add</button>
</div>
<div class="editor-field">
<table>
<thead>
<tr>
<th>Identifier Type</th>
<th>Value</th>
<th></th>
</tr>
</thead>
<!-- ko if: identifiers().length > 0 -->
<tbody data-bind="foreach: identifiers">
<tr>
<td>
<select data-bind="options: $root.identiferTypes,
optionsText: 'Name', optionsValue: 'Id', value: Key">
</select>
</td>
<td><input type="text" data-bind="value: Value"/></td>
<td><a href="#" class="ui-icon ui-icon-closethick" data-bind="click: $root.removeIdentifier">Remove</a></td>
</tr>
</tbody>
<!-- /ko -->
<!-- ko if: identifiers().length < 1 -->
<tbody>
<tr>
<td colspan="3"> No identifiers added.</td>
</tr>
</tbody>
<!-- /ko -->
</table>
@Html.HiddenFor(x => x.IdentifiersCount, new { data_bind = "value:identifiers().length" })<span data-bind="text:identifiers"></span>
@Html.ValidationMessageFor(x => x.IdentifiersCount)
</div>
</fieldset>
<p>
<input type="submit" value="Create" />
</p>
}
【问题讨论】:
-
如果您不使用 ko.utils 提交表单帖子,而是使用 $.ajax 序列化您的模型,这是否有效? firebug 显示的内容正在请求中传递。
-
@madcapnmckay 是的,它确实有效,使用 $.ajax 方法,一切都按预期工作。当使用正常的回发方法时,数据被传递到请求中,除了标识符显示为
identifiers: [{}]一个空数组外,一切看起来都很好。我发现如果我在保存时执行self.identifiers = ko.toJSON(self.identifiers());,则发布数据中的结果是:identifiers:"[{\"Value\":\"sdfsd\",\"Key\":\"4554f477-5a58-4e81-a6b9-7fc24d081def\"}]",所以它实际上是在传递数据,但结果是一样的。当我开始行动时,标识符不为空,但计数为 0。 -
@madcapnmckay JSON 看起来不正确,对吧?不应该有转义引号吗?当我执行
$.ajax方法时,请求有效负载中的数据周围没有转义引号,并且当我调试操作时,房间和 buildingCode 不包含转义引号值。但是当我发布他们的正常方式时,如上所示。您认为这与问题有关吗? -
不,它没有。我从未使用过 postJson 函数,我总是使用 $.ajax 和 stringify 发布 json(我见过的大多数示例也这样做)。如果您检查 KO 源,它实际上创建了一个表单元素并向其添加值然后提交。我会使用你自己的 ajax 函数,更简洁的方式是不要将表单帖子与 json 帖子混在一起。
-
不幸的是,我需要使用常规回发,根据这个示例knockoutjs.com/examples/gridEditor.html,它使用正常的回发,所以它应该可以工作。
标签: javascript asp.net-mvc json asp.net-mvc-3 knockout.js