我有主视图和部分视图:
// // 获取:/问题/添加/
public ActionResult Add()
{
return View();
}
//
// Post: /Question/GetAnswerContainers/
[HttpPost]
public ActionResult GetAnswerContainers(int count)
{
ViewBag.AnswerCount = count;
return PartialView();
}
主视图相当简单:
@using (@Html.BeginForm())
{
@Html.AntiForgeryToken()
<fieldset>
<legend>Add Question Form</legend>
<div id="question_answers">
@Html.LabelFor(m => m.AnswerCount)
@Html.TextBoxFor(m => m.AnswerCount,
new {
@class = "answer_count",
action = @Url.Action("GetAnswerContainers")
})<br/>
@Html.ValidationMessageFor(m => m.AnswerCount)<br/>
<div id="answers"></div>
</div>
<input type="submit" value="Add" />
</fieldset>
}
我的文本框也有 jQuery:
$(function () {
$('#question_answers input[type="text"].answer_count').keyup(function () {
var answerCount = $(this).val();
if (isNaN(answerCount))
return;
$.ajax({
type: 'POST',
data: { count: $(this).val() },
url: $(this).attr("action"),
timeout: 2000,
async: false,
success: function (data) {
removeAnswers();
addAnswers(data);
$('form').removeData('validator');
$('form').removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('form');
},
error: null
});
});
});
function addAnswers(data) {
var answersContainer = $('#question_answers #answers');
answersContainer.append($((data)));
}
部分观点:
@model Quiz.Models.Question.QuestionAnswer
@Html.LabelFor(m => m.AnswerText)
@for (var i = 0; i < ViewBag.AnswerCount; i++)
{
@Html.TextBoxFor(m => m.AnswerText)
@Html.ValidationMessageFor(m => m.AnswerText)
}
模型:
public class QuestionAnswer
{
[Required]
[Display(Name = "Answers")]
public string AnswerText { get; set; }
}
所以我的问题是标准的 asp.net 客户端验证无法处理 QuestionAnswer 模型的许多对象,它从for
循环中获取第一个文本框并将其用于验证所有部分视图。是否可以在客户端正确验证来自一个模型的多个对象?