我正在尝试了解响应式页面以及如何使用C#服务器和Web API 2.0,我受到了Ajax.BeginForm的诱惑。以下教程我已经到了这一步:
.cshtml:
@model LearningCancerAPICalls.Models.Player
<div id="report">
<div id="projectReport">
<div>
@{
Html.EnableClientValidation();
}
<a id="contact-us">Share Score!</a>
<div id="contact-form" class="hidden" title="Online Request Form">
@using (Ajax.BeginForm("", "", null, new AjaxOptions
{
HttpMethod = "POST",
Url = "http://localhost:52316/api/Player",
OnSuccess = "OnSuccess",
OnFailure = "OnFailure",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "reportContent"
}, new { id = "formId", name = "frmStandingAdd" }))
{
@Html.ValidationSummary(true)
@Html.LabelFor(m => m.PlayerName);
@Html.TextBoxFor(m => m.PlayerName);
@Html.ValidationMessageFor(model => model.PlayerName)
@Html.LabelFor(m => m.Email);
@Html.TextBoxFor(m => m.Email);
@Html.ValidationMessageFor(model => model.Email)
@Html.HiddenFor(m => m.PlayerId);
@Html.Hidden( "PlayerId");
<input type="submit" name="submit" value="Ok" />
<div id="divResponse">
</div>
}
</div>
</div>
</div>
<div id="reportContent">
</div>
</div>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script>
function OnSuccess() {
alert('Success');
resetValidation();
}
function OnFailure(ajaxContext) {
$('#projectReport').html(ajaxContext.responseText);
$('#reportContent').empty();
alert('Failure');
}
function resetValidation() {
//Removes validation from input-fields
$('.input-validation-error').addClass('input-validation-valid');
$('.input-validation-error').removeClass('input-validation-error');
//Removes validation message after input-fields
$('.field-validation-error').addClass('field-validation-valid');
$('.field-validation-error').removeClass('field-validation-error');
//Removes validation summary
$('.validation-summary-errors').addClass('validation-summary-valid');
$('.validation-summary-errors').removeClass('validation-summary-errors');
}
</script>
控制器:
[ResponseType(typeof(void))]
public IHttpActionResult PostPlayer(LearningCancerAPICalls.Models.Player player)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var model = LeaderBoardContext.Current.Players.FirstOrDefault(x => x.PlayerId == player.PlayerId);
if (model != null)
{
model.PlayerName = player.PlayerName;
model.Email = player.Email;
LeaderBoardContext.Current.Entry<Player>(player).State = EntityState.Modified;
}
else
{
LeaderBoardContext.Current.Players.Add(player);
}
try
{
LeaderBoardContext.Current.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
return BadRequest(ModelState);
}
return StatusCode(HttpStatusCode.NoContent);
}
班级:
public class Player
{
[Key]
public int PlayerId{ get; set; }
[Display(Name = "Player Name")]
[Required(ErrorMessage = "The Player name is required")]
public string PlayerName { get; set; }
[Display(Name = "Email address")]
[Required(ErrorMessage = "The email address is required")]
[Email(ErrorMessage = "The email address is not valid")]
public string Email { get; set; }
}
基于教程的各种融合和&amp;堆栈O Q&amp; As:
但我坚持的部分是“很好”的验证。目前,上述的最终结果是错误输入,两个字段消失,只显示消息。基于上面的代码实际上是有道理的。我是否必须手动填写验证字段,如果是这样,是否有一个简单的技巧或是否必须在家中滚动?让MS让Ajax.BeginForm失宠(我找不到很多关于如何在Web API 2.0中使用它的教程?
答案 0 :(得分:0)
所以我发现了&#34;电子邮件&#34;我在DataAnnotation包中使用的标签似乎无法正常工作。将其交换为EmailAddress标记并清理其他代码解决了我的问题!
所以现在我的代码的简单版本如下所示:
@model LearningCancerAPICalls.Models.Player
@{
Layout = null;
}
<div id="Aj3">
@{ var ajaxOptions = new AjaxOptions
{
HttpMethod = "POST",
Url = "http://localhost:52316/api/Player",
OnSuccess = "OnSuccess",
OnFailure = "OnFailure",
OnBegin = "OnBegin"
}; }
@using (Ajax.BeginForm("", "", ajaxOptions, new {novalidate = ""}))
{
@Html.LabelFor(m => m.PlayerName)
@Html.TextBoxFor(m => m.PlayerName)
@Html.ValidationMessageFor(m => m.PlayerName)
<br/>
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email)
@Html.ValidationMessageFor(m => m.Email)
@Html.HiddenFor(m => m.PlayerId)
<input type="submit"/>
}
</div>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script>
function OnBegin() {
}
function OnSuccess() {
}
function OnFailure(ajaxContext) {
}
</script>
基本上,当涉及客户端验证时,HTML.BeginForm和AJAX.BeginForm之间没有真正的区别,AJAX.Helper与WebAPI和AJAX之间也没有任何区别。使用标准MVC控制器。
要确保客户端验证有效,请将以下内容添加到web.config:
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
我还通过将脚本添加到BundleConfig.cs
中的包中来清理了一下bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate.js",
"~/Scripts/jquery.validate.unobtrusive.js"));
用
替换为JS文件列表@Scripts.Render("~/bundles/jqueryval")
这解决了所有客户端验证,但是从WebAPI进行额外的模型验证呢?好吧,它需要更多的工作,你需要解码JSON回来并手动添加 ,但除此之外,没有区别:)
我们在模型状态中有一个内部可重复使用的功能,我不能发布完整的代码,但它或多或少:
json = $.parseJSON(data.responseText);
$.each(json.ModelState, function (key, value) {
//get element
//add field error classes
}
或者,您可以选择在webApi中发送不属于模型状态的内容,您可以发送完全不同的JSON来处理。这些将进入&#34; OnFailure&#34; Json功能。在&#34; OnBegin&#34;中使用额外的清除逻辑功能
P.S。 &#34; novalidation&#34;添加属性是为了阻止Chrome等人添加自己的验证,请参阅: