2

I have this wiered behavior in my project and I've followed this, this and this links but with no success. Everytime my controller method gets hit while debugging, the model will be always null. Can anyone tell what else methods I can try to pass the model through form.serialize()

Here is my Model:

public class AddNewUser
{
     public string uname { get; set; }
     public string password { get; set; }
     public string Role { get; set; }
     public string fname { get; set; }
     public string lname { get; set; }
     public HttpPostedFileBase profilepic { get; set; }
     public string email { get; set; }
     public string contact { get; set; }
}

Here is my view:

@model AdminViewModel.AddNewUser
@{
    var uRole = TempData["UserRole"] as string;
    TempData.Keep("UserRole");
}

@using (Html.BeginForm("AddUser", "Admin", FormMethod.Post, new { id = "frmAddUser", @class = "form-admin col-lg-8 col-lg-offset-2" }))
{

    <h2 class="form-login-heading mar-pad">Add new user</h2>

     <label style="font-weight:normal" for="#txtuserName">Username *</label>
     @Html.TextBoxFor(m => m.uname, new {type="text",name="uname",tabindex="1",id="txtuserName", style="padding-right:20px", autocomplete="off", spellcheck="false",placeholder="Enter username", @class="form-control ip" })

     <label style="font-weight:normal" for="#txtPassword">Password *</label>

     @Html.PasswordFor(m => m.password, new { name = "password", tabindex = "2", id = "txtPassword", autocomplete = "off", spellcheck = "false", @class = "form-control ip", placeholder = "Enter password", data_tog = "tooltip", title = "Your Password must contain : <br />- at least 1 upper case character, <br /> - at least 1 lower case character, <br /> - at least 1 numerical character, <br /> - at least 1 special character.", data_placement = "top" })

     @if (uRole == "Admin")
     {

             <label style="font-weight:normal;margin-left:15px !important" for="#selectRole">Select Role *</label><br />
             <select id="selectRole" class="selectpicker show-menu-arrow full_wid col-md-12" tabindex="3" data-size="5">
                   <option value="0" selected disabled>Please select a role</option>
                   <option value="1">Admin</option>
                   <option value="2">Manager</option>
             </select>

             @Html.HiddenFor(m => m.Role, new { id="hdnRole", data_selected=""})

             <label style="font-weight:normal" for="#txtFName">First name *</label>
             @Html.TextBoxFor(m => m.fname, new { id="txtFname", style="padding-right:20px !important;", tabindex="4", autocomplete="off", spellcheck="false", placeholder="Enter user first name", @class="form-control ip"})

             <label style="font-weight:normal" for="#txtLName">Last name *</label>
             @Html.TextBoxFor(m => m.lname, new { id = "txtLname", style = "padding-right:20px !important;", tabindex = "5", autocomplete = "off", spellcheck = "false", placeholder = "Enter user last name", @class = "form-control ip"})

       }
       else
       {
             <label style="font-weight:normal" for="#txtFName">First name *</label>
             @Html.TextBoxFor(m => m.fname, new { id = "txtFname", style = "padding-right:20px !important;", tabindex = "3", autocomplete = "off", spellcheck = "false", placeholder = "Enter user first name", @class = "form-control ip" })

             <label style="font-weight:normal" for="#txtLName">Last name *</label>
             @Html.TextBoxFor(m => m.lname, new { id = "txtLname", style = "padding-right:20px !important;", tabindex = "4", autocomplete = "off", spellcheck = "false", placeholder = "Enter user last name", @class = "form-control ip" })
       }

     Upload image @Html.TextBoxFor(m => m.profilepic, new { type="file", id="userImageFile", tabindex=6, data_charset="file"})

     <label style="font-weight:normal" for="#txtUEmail">Email [optional]</label>
     @Html.TextBoxFor(m => m.email, new { id = "txtUEname", style = "padding-right:20px !important;", tabindex = "7", autocomplete = "off", spellcheck = "false", placeholder = "Enter user email[optional]", @class = "form-control ip" })

     <label style="font-weight:normal" for="#txtUContact">Contact [optional]</label>
     @Html.TextBoxFor(m => m.contact, new { id = "txtUContact", style = "padding-right:20px !important;", tabindex = "8", autocomplete = "off", spellcheck = "false", placeholder = "Enter user contact[optional]", @class = "form-control ip", data_maxlength="10" })

     <button class="btn btn-theme btn-block" name="add" onclick="javascript:AddUser(this);" tabindex="9" id="btnAddUser" type="submit"><i class="fa fa-save"></i> Save</button>

     <button class="btn btn-default btn-block" name="cancel" onclick="javascript: ResetAddUserForm('#frmAddUser');" tabindex="10" id="btnClear" type="button"><i class="fa fa-refresh"></i> Clear</button>

}

and here is my ajax call:

function AddUser(ctrl)
{
    var data = "";
    $("#frmAddUser").on("submit", function (e) {
        e.preventDefault();
        ValidateForm("#frmAddUser");
        var formContainer = $('#frmAddUser .text-danger');
        if ($(formContainer).text().length == 0) {
            $.ajax({
                url: '/Admin/AddUser',
                type: "POST",
                dataType:'json',
                contentType: "application/json",
                data: $('form#frmAddUser').serialize(),
                success: function (data) {
                    if (data.result) {
                        ResetForm('#frmAddUser');
                        toastr.success(data.message, "Success");
                    }
                    else {
                        toastr.error(data.message, "Failed");
                    }
                },
                error:
                function (data) {
                    toastr.error(data.message, "Failed");
                }
            });
        }

        $("#frmAddUser").unbind('submit');
        return false;
    });
}

and atlast my controller method:

[HttpPost]
  public ActionResult AddUser(AdminViewModel.AddNewUser usermodel) //->Always null
  {
       ......
  }

Waiting for any help!!

EDIT - I know this can be done using FormData instead of $('form').serialize() but I just want to try with this method!!

20
  • 1
    Is the model null or its properties null? Commented May 2, 2015 at 10:41
  • 1
    Cant spot anything obvious (although you have some pointless code like trying to set the name attributes of controls and a select which does not post back its value). What does console.log($('#frmAddUser').serialize()); return? Commented May 2, 2015 at 10:48
  • 1
    Why are you writing on('submit'.. inside AddUser()? Either write submit handler or the click event but not both. Commented May 2, 2015 at 10:51
  • 1
    Did you try adding debugger inside the AddUser() function and check whether it is being called? Commented May 2, 2015 at 10:58
  • 1
    You will also never post back any files from your form with this (you would need to use FormData to do so) Commented May 2, 2015 at 10:58

1 Answer 1

1

You can use Ajax.BeginForm instead of Html.BeginForm

Html vs Ajax beginform Reference: here

Sign up to request clarification or add additional context in comments.

1 Comment

I appreciate your answer but I wanted to achieve that with what I've already implemented! Anyways thanks for your time... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.