【问题标题】:Submitting the form always calls get action method instead of post action method提交表单总是调用 get action 方法而不是 post action 方法
【发布时间】:2015-06-06 06:46:55
【问题描述】:

您好,我的控制器 (asp.net 4.5.1 mvc 5) 中有以下代码,允许用户在我的网站上注册。一切工作正常,但我添加了另一个控制器和另一个服务,现在每当我尝试注册它在提交时所做的一切都会再次重定向回空白表单。调试后,下面控制器中的post action方法永远不会被调用

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            UserManager.AddClaim(user.Id, new Claim(ClaimTypes.GivenName, model.FirstName));
            var service = new GRCMemberService(HttpContext.GetOwinContext().Get<ApplicationDbContext>());
            service.CreateGRCMember(model.FirstName, model.LastName, model.Address1, model.Address2, model.City, model.County, model.Postcode, model.Telephone, model.DateOfBirth, model.Dietary, model.CompLicenceNo, model.SelectedLicenceTypeId, model.NOKFirstName, model.NOKLastName, model.NOKTelephone, model.RelationshipTypeId, model.OtherOrgsGRC, model.OtherClubEvents, model.OtherOrgsOutside, user.Id);
            //var currentUser = UserManager.FindByName(user.Id);
            //var newrole = ("GRCMember");
            //var roleresult = UserManager.AddToRole(currentUser.Id, newrole);
            await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

            // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
            // Send an email with this link
            // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
            // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

            return RedirectToAction("Index", "Home");
        }  
        AddErrors(result);
    }
    // If we got this far, something failed, redisplay form 
    return View(model); 
}

相反,每次提交表单时都会调用下面的 get 操作方法:

[AllowAnonymous]
public ActionResult Register()
{
    return View();
}

知道有什么问题吗?

下面是我的 ViewModel 和 View 代码。

视图模型

public class RegisterViewModel
{
    [Required]
    [Display(Name = "First Name")]
    [StringLength(160, ErrorMessage = "First Name cannot be longer than 160 characters.")]
    public string FirstName { get; set; }

    [Required]
    [Display(Name = "Last Name")]
    [StringLength(160, ErrorMessage = "Last Name cannot be longer than 160 characters.")]
    public string LastName { get; set; }

    [Required]
    [Display(Name = "Address 1")]
    [StringLength(160, ErrorMessage = "Address1 cannot be longer than 160 characters.")]
    public string Address1 { get; set; }

    [Display(Name = "Address 2")]
    [StringLength(160, ErrorMessage = "Address2 cannot be longer than 160 characters.")]
    public string Address2 { get; set; }

    [Required]
    [Display(Name = "City")]
    [StringLength(100, ErrorMessage = "City cannot be longer than 100 characters.")]
    public string City { get; set; }

    [Display(Name = "County")]
    [StringLength(100, ErrorMessage = "County cannot be longer than 100 characters.")]
    public string County { get; set; }

    [Required]
    [Display(Name = "PostCode")]
    [StringLength(10, ErrorMessage = "Postcode cannot be longer than 10 characters.")]
    public string Postcode { get; set; }

    [Required]
    [Display(Name = "Telephone")]
    [StringLength(20, ErrorMessage = "Telephone cannot be longer than 20 characters.")]
    public string Telephone { get; set; }

    [StringLength(20, ErrorMessage = "Competition Licence Number cannot be longer than 20 characters.")]
    [Display(Name = "Licence Number")]
    public string CompLicenceNo { get; set; }

    [Display(Name = "Licence Type")]
    public int? SelectedLicenceTypeId { get; set; }

    [StringLength(200, ErrorMessage = "Competition Licence Number cannot be longer than 20 characters.")]
    [Display(Name = "Dietary Requirements - For events")]
    public string Dietary { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "Next of Kin Name cannot be longer than 100 characters.")]
    [Display(Name = "Next of kin First Name")]
    public string NOKFirstName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "Next of Kin Name cannot be longer than 100 characters.")]
    [Display(Name = "Next of kin Last Name")]
    public string NOKLastName { get; set; }

    [Required]
    [StringLength(20, ErrorMessage = "Next of Kin Telephone cannot be longer than 20 characters.")]
    [Display(Name = "Next of kin Telephone")]
    public string NOKTelephone { get; set; }

    [Display(Name = "Next of kin Relationship")]
    public int? RelationshipTypeId { get; set; }

    [Required]
    [Display(Name = "Date of Birth")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:dd/mm/yyyy}", ApplyFormatInEditMode = true)]
    public DateTime DateOfBirth { get; set; }

    [Display(Name = "Allow other organisations on Grass Roots Clicks to contact you?")]
    public bool OtherOrgsGRC { get; set; }

    [Display(Name = "Allow other clubs you are a member of or ones whose events you enter to contact you?")]
    public bool OtherClubEvents { get; set; }

    [Display(Name = "Allow other organisations outside of Grass Roots Clicks that we are working with to contact you?")]
    public bool OtherOrgsOutside { get; set; }

    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [EmailAddress]
    [Display(Name = "Confirm email")]
    [Compare("Email", ErrorMessage = "Your email and confirmation email do not match.")]
    public string ConfirmEmail { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}

查看

@model GRCWebApp.Models.RegisterViewModel

@{
    ViewBag.Title = "Register";
}

<h2 class="text-success">@ViewBag.Title</h2>
<div class="row">
    <div class="col-md-7">
        <div class="well bs-component">
            <form class="form-horizontal">
                <fieldset>
                    <section id="loginForm">
                        @using (Html.BeginForm("Register", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                        {
                            @Html.AntiForgeryToken()
                            <hr />
                            @Html.ValidationSummary("", new { @class = "text-danger" })

                            <h3 class="text-success col-md-offset-1">Name &amp; Address</h3>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-3  col-md-offset-1">
                                        @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control", placeholder = "John" } })
                                        @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-4 col-md-offset-2">
                                        @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control", placeholder = "Smith" } })
                                        @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-5 col-md-offset-1">
                                        @Html.LabelFor(model => model.Address1, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.Address1, new { htmlAttributes = new { @class = "form-control", placeholder = "1 Apple Road" } })
                                        @Html.ValidationMessageFor(model => model.Address1, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-5">
                                        @Html.LabelFor(model => model.Address2, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.Address2, new { htmlAttributes = new { @class = "form-control", placeholder = "Neighbourhood" } })
                                        @Html.ValidationMessageFor(model => model.Address2, "", new { @class = "text-danger" })
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-5 col-md-offset-1">
                                        @Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control", placeholder = "Some Town" } })
                                        @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-5">
                                        @Html.LabelFor(model => model.County, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.County, new { htmlAttributes = new { @class = "form-control", placeholder = "Someshire" } })
                                        @Html.ValidationMessageFor(model => model.County, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-3 col-md-offset-1">
                                        @Html.LabelFor(model => model.Postcode, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.Postcode, new { htmlAttributes = new { @class = "form-control", placeholder = "AA1 2BB" } })
                                        @Html.ValidationMessageFor(model => model.Postcode, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>
                            <h3 class="text-success col-md-offset-1">Contact Details</h3>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.Telephone, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.Telephone, new { htmlAttributes = new { @class = "form-control", placeholder = "01234 567890" } })
                                        @Html.ValidationMessageFor(model => model.Telephone, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control", placeholder = "me@provider.com" } })
                                        @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.ConfirmEmail, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.ConfirmEmail, new { htmlAttributes = new { @class = "form-control", placeholder = "me@provider.com" } })
                                        @Html.ValidationMessageFor(model => model.ConfirmEmail, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>
                            <h3 class="text-success col-md-offset-1">Competition Licence</h3>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.CompLicenceNo, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.CompLicenceNo, new { htmlAttributes = new { @class = "form-control", placeholder = "123456" } })
                                        @Html.ValidationMessageFor(model => model.CompLicenceNo, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-3 col-md-offset-1">
                                        @Html.LabelFor(model => model.SelectedLicenceTypeId, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.SelectedLicenceTypeId, new { htmlAttributes = new { @class = "form-control" } })
                                        @Html.ValidationMessageFor(model => model.SelectedLicenceTypeId, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>
                            <h3 class="text-success col-md-offset-1">Personal Details</h3>
                            <h4 class="text-success col-md-offset-1">Why do we need this information?</h4>
                            <p>To make it easier for you to enter events here on Grass Roots Clicks we gatther certain information that we can then populate into your entry. Why do we need a date of birth? Organisers gain great benefit form knowing what ages are taking part in their events. We dont share your date of birth, we use your current age to help the organisers and also tailor the entry form to you e.g. if your under 18 we'll ask you for parental permission for some events.</p>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-3 col-md-offset-1">
                                        @Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control", placeholder = "01/12/80" } })
                                        @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.NOKFirstName, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.NOKFirstName, new { htmlAttributes = new { @class = "form-control", placeholder = "Jane" } })
                                        @Html.ValidationMessageFor(model => model.NOKFirstName, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.NOKLastName, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.NOKLastName, new { htmlAttributes = new { @class = "form-control", placeholder = "Smith" } })
                                        @Html.ValidationMessageFor(model => model.NOKLastName, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.NOKTelephone, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.NOKTelephone, new { htmlAttributes = new { @class = "form-control", placeholder = "07234 567890" } })
                                        @Html.ValidationMessageFor(model => model.NOKTelephone, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.RelationshipTypeId, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.RelationshipTypeId, new { htmlAttributes = new { @class = "form-control" } })
                                        @Html.ValidationMessageFor(model => model.RelationshipTypeId, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-7 col-md-offset-1">
                                        @Html.LabelFor(model => model.Dietary, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.Dietary, new { htmlAttributes = new { @class = "form-control", placeholder = "Vegetarian" } })
                                        @Html.ValidationMessageFor(model => model.Dietary, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>
                            <h3 class="text-success col-md-offset-1">Password</h3>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })
                                        @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
                                    </div>
                                    <div class="col-md-4 col-md-offset-1">
                                        @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label" })
                                        @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })
                                        @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>
                            <h3 class="text-success col-md-offset-1">Contact</h3>
                            <div class="form-group">
                                <div class="row">
                                    <div class="col-md-9 col-md-offset-1">
                                        @Html.LabelFor(model => model.OtherOrgsGRC, htmlAttributes: new { @class = "control-label" })
                                    </div>
                                    <div class="col-md-1">
                                        @Html.CheckBoxFor(model => model.OtherOrgsGRC, new { @checked = "checked" })
                                        @Html.ValidationMessageFor(model => model.OtherOrgsGRC, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-9 col-md-offset-1">
                                        @Html.LabelFor(model => model.OtherClubEvents, htmlAttributes: new { @class = "control-label" })
                                    </div>
                                    <div class="col-md-1">
                                        @Html.CheckBoxFor(model => model.OtherClubEvents, new { @checked = "checked" })
                                        @Html.ValidationMessageFor(model => model.OtherClubEvents, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-9 col-md-offset-1">
                                        @Html.LabelFor(model => model.OtherOrgsOutside, htmlAttributes: new { @class = "control-label" })
                                    </div>
                                    <div class="col-md-1">
                                        @Html.CheckBoxFor(model => model.OtherOrgsOutside, new { @checked = "checked" })
                                        @Html.ValidationMessageFor(model => model.OtherOrgsOutside, "", new { @class = "text-danger" })
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-10 col-md-offset-1">
                                    <input type="submit" value="Register" class="btn btn-success btn-lg" />
                                </div>
                            </div>
                        }
                    </section>
                </fieldset>
            </form>
        </div>
    </div>


    <div class="col-md-4 panel panel-success">
        <div class="panel-heading">
            <h3 class="panel-title " align="center">Use another service to register</h3>
        </div>

        @Html.Partial("_ExternalLoginsListPartial", new GRCWebApp.Models.ExternalLoginListViewModel { ReturnUrl = ViewBag.ReturnUrl })

    </div>
</div>


@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/bundles/bootstrap")
<script type="text/javascript">
    $("#DateOfBirth").datepicker({
        format: "dd/mm/yyyy",
        startDate: "-120y",
        endDate: "-10y",
        startView: 2,
        calendarWeeks: true,
        defaultViewDate: { year: 1975, month: 01, day: 01 }
    });
    </script>
    }

【问题讨论】:

  • AddErrors(result) 是做什么的?
  • 因为它的代码我是从教程中复制的,恐怕我不知道,我确实把它拿出来了,没有任何改变
  • 这里是它的定义
  • private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } }
  • 您的控制器代码不完整。 if (ModelState.IsValid) 块之后是否有任何代码?原因可能是ModelState.IsValid 为假,或者result.Succeeded 为假。

标签: c# asp.net-mvc asp.net-mvc-5


【解决方案1】:

我通过删除视图开头的表单、字段集和部分标签来解决问题。

感谢 ekad 帮助调试问题

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-10-15
  • 2019-01-10
  • 1970-01-01
  • 1970-01-01
  • 2020-12-31
  • 1970-01-01
  • 2016-02-29
  • 1970-01-01
相关资源
最近更新 更多