9

I have the following model:

public class RegisterUseraccount
{
    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "E-Mail-Adresse")]
    public string Email { get; set; }

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

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

    [Required]
    [DataType(DataType.Password)]
    [MinLength(5)]
    [Display(Name = "Passwort")]
    public string Password { get; set; }

    ...
}

And the following view:

@using (Html.BeginForm("Register", "Useraccount", FormMethod.Post, new { id = "registerUseraccountForm", @class = "ym-form" }))
{
    @Html.ValidationSummary(true)        

    <div class="ym-grid">
        <div class="ym-g50 ym-gl">
            <div class="ym-fbox-text">
                @Html.LabelForRequired(model => model.RegisterUseraccount.FirstName, null)               
                @Html.EditorFor(model => model.RegisterUseraccount.FirstName, new { required = "required", name = "firstName" })
                @Html.ValidationMessageFor(model => model.RegisterUseraccount.FirstName)                  
            </div>
        </div>
    ...

and my JavaScript

function sendForm(target) {
    alert(data);
    $.ajax({
        url: target,
        type: "POST",
        contentType: 'application/json',
        data: $("#registerUseraccountForm").serialize(),
        success: ajaxOnSuccess,
        error: function (jqXHR, exception) {
            alert('Error message.');
        }
    });

This is the result of the serialization:

RegisterUseraccount.FirstName=Peter&RegisterUseraccount.LastName=Miller&RegisterUseraccount.Email=miller%40gmail.com&RegisterUseraccount.Password=admin

This is my controller method I'm trying to POST to:

[HttpPost]
public ActionResult Register(RegisterUseraccount registerUseraccount)
{
    ...
}

... but the data doesn't arrive at the method, I get an error 404. I think the modelbinder can't work.

What works is data which is sent with the name firstName=Peter, but what actually is sent is RegisterUseraccount.FirstName=Peter.

How can I handle this problem?

4

3 回答 3

21

删除contentType: 'application/json',并修改它更好(从我的角度来看)

$('#registerUseraccountForm').submit(function () {
    if ($(this).valid()) {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            beforeSend: function () {

            },
            complete: function () {

            },
            ...
于 2013-05-23T15:27:34.207 回答
2

也许你有这个模型

public class YourModel
{
    public RegisterUseraccount RegisterUseraccount { get; set; }
}

在这种情况下,您必须放置与您的操作相对应的模型:

[HttpPost]
public ActionResult Register(YourModel model)
{
    var registerUseraccount = model.RegisterUseraccount;
    ...
}

或者:

@using (Html.BeginForm("Register", "Useraccount", FormMethod.Post, new { id = "registerUseraccountForm", @class = "ym-form" }))
{
   @{ Html.RenderPartial("RegisterUseraccount"); }
}

RegisterUseraccount.cshtml

@model YourNamespace.RegisterUseraccount

@Html.ValidationSummary(true)        

<div class="ym-grid">
    <div class="ym-g50 ym-gl">
        <div class="ym-fbox-text">
            @Html.LabelForRequired(model => model.FirstName, null)               
            @Html.EditorFor(model => model.FirstName, new { required = "required", name = "firstName" })
            @Html.ValidationMessageFor(model => model.FirstName)                  
        </div>
    </div>

但是您必须更改一些内容,例如@Html.ValidationSummary (true).

编辑

或者最简单的:

data: $("#registerUseraccountForm").serialize().replace("RegisterUseraccount.",""),

编辑二

data: $("#registerUseraccountForm").serialize().replace(/RegisterUseraccount./g,""),
于 2013-05-23T16:42:37.110 回答
0

使用 jQuery ajax 发布数据有两种变体。

  1. 使用 $.ajax
  2. 使用 $.post

下面展示了如何使用 $.post

   $('#btn-register').click(function () {

        var $form = $('#registerUseraccountForm');

         if ($form.valid()) {
        
               var url = $form.attr('action'),
                   fd = $form.serialize();
    
                $.post(url, fd).done(function (result) {
                    if (result) {
                        Swal.fire(
                            'Success!',
                            'User registered successfully',
                            'success'
                        )
                    } else
                        Swal.fire(
                            'Failed!',
                            'Failed to register user',
                            'error'
                        )
                }).fail(function () {
                    Swal.fire(
                        'Failed!',
                        'Failed to register user',
                        'error'
                    )
                });
            }else{
                Swal.fire(
                    'Invalid!',
                    'Form contains invalid data',
                    'error'
                )
            }
        });

我会说,在不需要像使用 $.ajax 那样进行额外配置的地方,只需序列化表单并发布即可。当然,如果您已经为字段定义了验证,请验证表单。很简单!

于 2022-02-23T04:13:48.127 回答