3

However, in the controller the params are always null/default values. Please see my code below and let me know if I am making a silly mistake or something.

Plz see image

Here is my controller's action method:

[HttpPost]
public JsonResult AjaxMethodTemp([FromBody]UserAccount user)
{
    //string Name = name + DateTime.Now.ToString();

    //return Json(Name);
    try
    {
        //if (ModelState.IsValid)
        //{
            _context.userAccount.Add(user);
            _context.SaveChanges();
            ModelState.Clear();

            ViewBag.Massege = user.FirstName + "_" + user.LastName + " is Successfully Registered";
        //}
    }
    catch (DbUpdateException /* ex */)
    {
        //Log the error (uncomment ex variable name and write a log.
        ModelState.AddModelError("", "Unable to save changes. " +
            "Try again, and if the problem persists " +
            "see your system administrator.");
    }
    return Json(user.FirstName + "_" + user.LastName + " is Successfully Registered");

}

Here is my AJAX post:

function SaveCity() {
    debugger
    var $form = $('#contactForm');
    $form.removeData('validator');
    $form.removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parse($form);
    $form.validate();
    if ($form.valid()) {

        $.ajax({
            type: "POST",
            url: "/Home/AjaxMethodTemp",
            //url:"/api/users",
            contentType: "application/json; charset=utf-8",
            data:
                {
                    Password: "abc",
                    UserName: "abc",
                    Email: "[email protected]",
                    FirstName: "abc",
                    LastName: "abc"
                },
            //data: JSON.stringify({
            //    FirstName: $('#FirstName').val(),
            //    LastName: $("#LastName").val(),
            //    Email: $("#Email").val(),
            //    UserName: $("#UserName").val(),
            //    Password: $("#Password").val()
            //}),
            success: function (data) {
            }

        });

    }
}

Here is my Form Data:

<form id="contactForm">
    @* asp-controller="Home" asp-action="AjaxMethod method="post""*@
    @if (ViewBag.Massege != null)
    {
        <div class="form-control">
            <div class="col-md-10">@ViewBag.Massege</div>
        </div>
    }

    <div class="form-group">
        <label asp-for="FirstName" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="FirstName" id="FirstName" class="form-control" />
            <span asp-validation-for="FirstName" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="LastName" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="LastName" id="LastName" class="form-control" />
            <span asp-validation-for="LastName" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="Email" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="Email" id="Email" class="form-control" />
            <span asp-validation-for="Email" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="UserName" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="UserName" id="UserName" class="form-control" />
            <span asp-validation-for="UserName" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="Password" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="Password" id="Password" class="form-control" />
            <span asp-validation-for="Password" class="text-danger"></span>
        </div>
    </div>
    <div class="form-group">
        <label asp-for="ConfirmPassword" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="ConfirmPassword" class="form-control" />
            <span asp-validation-for="ConfirmPassword" class="text-danger"></span>
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            @*<button type="submit" class="btn btn-default" id="btn1">Register</button>*@

            @*<input type="button" id="btnGet" value="Get Current Time" />*@
            <input type="submit" name="Sumbit" onclick="SaveCity(); return false;" />
            @*<a class="delete-link" h>Delete</a>*@
        </div>
    </div>
</form>

Here is the Model :

public class UserAccount
{
    [Key]
    public int UserID { get; set; }

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

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

    [Required(ErrorMessage ="Email Required")]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [Required(ErrorMessage ="User Name Required")]
    public string UserName { get; set; }

    [Required(ErrorMessage ="Password Required")]
    [DataType(DataType.Password)]
    public string Password { get; set; }

    [Compare("Password",ErrorMessage ="Password Not Match")]
    [DataType(DataType.Password)]
    public string ConfirmPassword { get; set; }
}

Any one have idea than plz help me...

8
  • In what class your AjaxMethodTemp is? What class it inherits from? Are you using MVC or Web API as your underlying framework? I guess you are mixing two of them Commented Mar 1, 2017 at 5:41
  • AjaxMethodTemp is HomeConroller Method, and i m use MVC . Commented Mar 1, 2017 at 5:50
  • have you any idea of how to save data using ajax call in mvc ? Commented Mar 1, 2017 at 5:51
  • What happens when you try with JSON.stringify({...});? Commented Mar 1, 2017 at 6:36
  • 2
    JSON.stringify({...}) is able to post values when I tried your code. Commented Mar 1, 2017 at 6:55

1 Answer 1

0

Try this,

var UserAccount{
    Password: "abc",
    UserName: "abc",
    Email: "[email protected]",
    FirstName: "abc",
    LastName: "abc"
};

 $.ajax({
      type: "POST",
      url: "/Home/AjaxMethodTemp",                      
      data: { user: UserAccount},           
      success: function (data) {
        alert("SUCCESS");
      }    
  });
Sign up to request clarification or add additional context in comments.

1 Comment

You can try with JSON.stringify({...});

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.