Model binding with jquery ajax serialize not working

后端 未结 2 618
不思量自难忘°
不思量自难忘° 2021-02-06 03:32

I have the following model:

public class RegisterUseraccount
{
    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = \"E-Mail-Adresse\")]
             


        
相关标签:
2条回答
  • 2021-02-06 03:42

    Maybe you have this model

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

    In this case you have to put the model that corresponds to your action:

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

    Or:

    @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>
    

    but you'll have to change some things like @Html.ValidationSummary (true).

    Edit

    or most simple:

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

    Edit II

    data: $("#registerUseraccountForm").serialize().replace(/RegisterUseraccount./g,""),
    
    0 讨论(0)
  • 2021-02-06 03:46

    remove contentType: 'application/json', and modify it to better (from my perspective)

    $('#registerUseraccountForm').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                beforeSend: function () {
    
                },
                complete: function () {
    
                },
                ...
    
    0 讨论(0)
提交回复
热议问题