解答: 替换这一行:
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\"}]"
但是,调试操作时会出现同样的问题。我也试过jsoning整个模型(如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-ified两次,因为每个字母或字符都是它在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>
}
答案 0 :(得分:1)
我想我已经找到了问题或者至少缩小了问题的范围。可编辑的网格示例使用简单的js对象来表示礼物。您正在使用带有子可观察对象的Identifier对象。似乎如果我们更新网格示例以使用更复杂的类型,它也会以与示例相同的方式中断。这可能是设计或错误。
我认为唯一的解决方案是编写自己的映射函数来提交表单。
希望这有帮助。