全体として、MVC3 に組み込まれているクライアント側の検証を、カスタムで作成した Ajax コードで使用できるようにしたいと考えています。HTML.BeginForm()
( &の両方を使用して作成されたフォームで利用可能な検証について話しているAjax.BeginForm()
)
私のモデルは次のようになります:
public class BrandVewModel
{
public int ID { get; set; }
[Display(Name = "Brand Name")]
[Required(ErrorMessage = "Please fill in the blank!")]
[StringLength(40, ErrorMessage = "The name must not be more than 40 characters long!")]
public string Name { get; set; }
}
そして、私のビューは次のようになります:
@using (Ajax.BeginForm("Insert_Brand", "Admin", FormMethod.Post, new AjaxOptions { UpdateTargetId = "result" }))
{
@Html.HiddenFor(model => model.ID)
@Html.ValidationMessageFor(model => model.Name)
@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name)
<input value="Create" type="submit" name="Create New Brand" />
<div id="result"></div>
}
ご覧のとおり、Ajax.BeginForm()
どちらが良いかを使用しています。明らかに、私のビューモデルに関して、ユーザーが名前フィールドを空白のままにして送信ボタンをクリックすると、フォームデータがサーバーに送信されることなく、対応するエラーが表示されます! (jQueryのおかげで、クライアント側のフォーム検証であるため)
ただし、以下に示すような単純なフォーム ( の代わりにAjax.BeginForm()
) が必要であり、クライアント側の検証機能もすべて備えている必要があります。
<form method="post" action="@Html.Action("Insert_Brand","Admin")">
@Html.HiddenFor(model => model.ID)
@Html.ValidationMessageFor(model => model.Name)
@Html.LabelFor(model => model.Name)
@Html.TextBoxFor(model => model.Name)
<a onclick="CreateBrand()">Create Brand</a>
</form>
// honestly I have no idea what 'custom-written ajax coding', or what I do here is called :p
<script type="text/javascript" >
function CreateBrand() {
var item = { Brand: { Name:$('#Name').val()} };
$.ajax({
url: '/Admin/Insert_Brand',
type: "POST",
data: JSON.stringify(item),
dataType: "text json",
contentType: "application/json; charset=utf-8",
success: function (t) {
console.log(t);
$("#result").html(t);
return;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("Failed!");
console.log("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
}
});
}
</script>
私が言ったように、この種の ajax フォーム投稿を使用する場合、ユーザーに表示されるすべての適切な検証メッセージが必要です。しかし、どうすればそれを達成できるかわかりません...
何か方法はありますか?