好的,所以这个问题很老了......但我想做类似的事情,我找到了一个适合我的解决方案。也许它可以帮助其他人。
我有一个List<QuestionType>,我用它填写下拉列表。我想将该选择放入我在表单中创建的Question 对象的QuestionType 属性中。我使用Knockout.js 进行选择绑定。当用户选择一个对象时,这会将self.QuestionType 淘汰可观察属性设置为QuestionType 对象。
<select class="form-control form-control-sm"
data-bind="options: QuestionTypes, optionsText: 'QuestionTypeText', value: QuestionType, optionsCaption: 'Choose...'">
</select>
我有一个隐藏字段来保存这个对象:
@Html.Hidden("NewQuestion.QuestionTypeJson", Model.NewQuestion.QuestionTypeJson)
在订阅 observable 时,我将隐藏字段设置为对象的 JSON.stringify-ed 版本。
self.QuestionType.subscribe(function(newValue) {
if (newValue !== null && newValue !== undefined) {
document.getElementById('NewQuestion_QuestionTypeJson').value = JSON.stringify(newValue);
}
});
在Question 对象中,我有一个名为QuestionTypeJson 的字段,当用户选择问题类型时会填充该字段。我使用这个字段来获取Question 对象中的QuestionType,如下所示:
public string QuestionTypeJson { get; set; }
private QuestionType _questionType = new QuestionType();
public QuestionType QuestionType
{
get => string.IsNullOrEmpty(QuestionTypeJson) ? _questionType : JsonConvert.DeserializeObject<QuestionType>(QuestionTypeJson);
set => _questionType = value;
}
因此,如果QuestionTypeJson 字段包含某些内容,它将反序列化并将其用于QuestionType,否则它将仅使用支持字段中的内容。
我基本上已经将一个 JavaScript 对象“传递”给我的模型,而没有使用 Razor 或 Ajax 调用。不使用Knockout.js,您可能可以做类似的事情,但这就是我正在使用的......