ASP.NET MVC 5表单验证

本文关键字:表单 验证 MVC NET ASP | 更新日期: 2023-09-27 18:07:20

我是ASP新手。. NET MVC和使用版本5。我在布局中创建了一个表单,但我无法让它在视图上显示验证错误。它将正确地发送到动作,如果模型有效,它将执行。如果模型无效,我将得到以下错误。

我希望有人能给我指出正确的方向。提前感谢!
Server Error in '/' Application.
The view 'ContactSubmit' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/ContactSubmit.aspx
~/Views/Home/ContactSubmit.ascx
~/Views/Shared/ContactSubmit.aspx
~/Views/Shared/ContactSubmit.ascx
~/Views/Home/ContactSubmit.cshtml
~/Views/Home/ContactSubmit.vbhtml
~/Views/Shared/ContactSubmit.cshtml
~/Views/Shared/ContactSubmit.vbhtml

这是我使用的模型:

public partial class Lead
{
    [Key]
    public int LeadId { get; set; }
    [Required]
    [StringLength(50, MinimumLength=2, ErrorMessage="* A valid first name is required.")]
    [Display(Name="First Name")]
    public string FirstName { get; set; }
    [Required]
    [StringLength(50, MinimumLength=2, ErrorMessage="* A valid last name is required.")]
    [Display(Name="Last Name")]
    public string LastName { get; set; }
    [Required]
    [StringLength(50, MinimumLength=2, ErrorMessage="* A valid company is required.")]
    public string Company { get; set; }
    [Required]
    [StringLength(50)]
    [EmailAddress(ErrorMessage="* A valid email address is required.")]
    public string Email { get; set; }
    [Required]
    [StringLength(15, MinimumLength=9, ErrorMessage="* A valid phone nunber is required.")]
    [Phone(ErrorMessage="Please enter a valid phone number.")]
    public string Phone { get; set; }
}

这是我在Home控制器中的代码:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ContactSubmit(
    [Bind(Include = "FirstName, LastName, Company, Email, Phone")]
    Lead lead)
{
    try
    {
        if (ModelState.IsValid)
        {
            lead.Tenant = SessionManager.Get<Tenant>(Constants.SessionTenant);
            lead.Refferer = SessionManager.Get<string>(Constants.SessionRefferal);
            DataStoreManager.AddLead(lead);
            return RedirectToAction("SubmissionConfirmed", lead);
        }
    }
    catch (DataException /* dex */)
    {
        ModelState.AddModelError("", "Unable to perform action. Please contact us.");
        return RedirectToAction("SubmissionFailed", lead);
    }
    return View(lead);
}
[HttpGet]
public ActionResult ContactSubmit()
{
    return View();
}

这是我在布局中创建的样式:

               @using (Html.BeginForm("ContactSubmit", "Home", FormMethod.Post))
                    {
                        @Html.AntiForgeryToken()
                        <fieldset>
                            <div class="editor-label">
                                @Html.LabelFor(m => m.FirstName)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(m => m.FirstName)
                                @Html.ValidationMessageFor(m => m.FirstName)
                            </div>
                            <div class="editor-label">
                                @Html.LabelFor(m => m.LastName)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(m => m.LastName)
                                @Html.ValidationMessageFor(m => m.LastName)
                            </div>
                            <div class="editor-label">
                                @Html.LabelFor(m => m.Company)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(m => m.Company)
                                @Html.ValidationMessageFor(m => m.Company)
                            </div>
                            <div class="editor-label">
                                @Html.LabelFor(m => m.Email)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(m => m.Email)
                                @Html.ValidationMessageFor(m => m.Email)
                            </div>
                            <div class="editor-label">
                                @Html.LabelFor(m => m.Phone)
                            </div>
                            <div class="editor-field">
                                @Html.EditorFor(m => m.Phone)
                                @Html.ValidationMessageFor(m => m.Phone)
                            </div>
                            <div class="masthead-button-wrapper">
                                <input class="btn btn-warning" type="submit" value="Submit" />
                            </div>
                        </fieldset>
                    }

ASP.NET MVC 5表单验证

你的代码中有一个错误,我没有首先注意到。在get方法中使用-

return View();

这意味着你的视图不允许参数但是当出现错误时,你使用-

return View(lead);

在这种情况下,MVC正在寻找具有相同名称的视图,但它也接受Lead类型的参数,并且它失败了,因为没有该选项的视图,并且唯一找到的视图不接受从Get方法中看到的参数。如果没有错误,则重定向到-

return RedirectToAction("SubmissionConfirmed", lead);

和带参数的View不需要搜索,因此没有错误。

因此,更改视图以接受Lead的参数并相应地更改get方法。

这可能会有帮助。-

[HttpGet]
public ActionResult ContactSubmit()
{
    var lead = new Lead();
    return View(lead);
}

并在视图中添加

@model Lead

在顶部

EDIT:由于您正在重定向,因此您应该知道ModelState在每个请求中都被初始化,因此重定向会自动清除它。如果使用客户端验证,则必须使用其他方法来传递modelstate,或者更好的方法。