简体   繁体   中英

Data is not sent from view (ajax) to controller (c#)

I'm new to AJAX, and I don't understand, why my data was not sent to controller. So, on my View I have two input forms and a button:

HTML:

<input type="text" name="AddName">
<input type="text" name="AddEmail"> 
<button class="btn btn-mini btn-primary" type="button" name="add_btn" onclick="DbAdd()">Add</button>

I need after button "add_btn" clicked take data from these two inputs and send them to controller.

JavaScript:

<script type="text/javascript">
    function DbAdd()
    {
        // Get some values from elements on the page:
        var $form = $(this),
            addedName = $form.find("input[name='AddName']").val(),
            addedEmail = $form.find("input[name='AddEmail']").val();

        $("#UserTable").html("<div>Please Wait...</div>");
        $.ajax(
        {
            type: "POST",
            url: "Save",
            data:
                {
                    name: addedName, email: addedEmail,
                },
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: OnSuccess,
            error: OnError
        });
}

And this is my controller's method "Save" (I need to save data got from ajax to my DB):

[HttpPost]
public ActionResult Save(User userinfo)
{
    string message = "";

    using (var uc = new UserContext())
    {
        uc.UserList.Add(userinfo);
        uc.SaveChanges();
        message = "Successfully Saved!";
    }

    if (Request.IsAjaxRequest())
    {
        return new JsonResult { Data = message };
    }
    else
    {
        ViewBag.Message = message;
        return View(userinfo);
    }
} 

The problem is that when I put a break point to my controller's method, I don't receive data from ajax, null's only. So I add an empty record to DB. Any suggestions?

Looks like $form.find("input[name='AddName']").val() and $form.find("input[name='AddEmail']").val() both return null. You should use $("input[name='AddName']").val() and $("input[name='AddEmail']").val() instead. Change the definition of DbAdd() to below

<script type="text/javascript">
    function DbAdd()
    {
        // Get some values from elements on the page:
        var addedName = $("input[name='AddName']").val(),
            addedEmail = $("input[name='AddEmail']").val();

        var user = { Name: addedName, Email: addedEmail };

        $("#UserTable").html("<div>Please Wait...</div>");
        $.ajax(
        {
            type: "POST",
            url: "Save",
            data: JSON.stringify({ userinfo: user }),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: OnSuccess,
            error: OnError
        });
    }
</script>

There is an extra comma which may be causing syntax error:

data:
{
  name: addedName, email: addedEmail, //<------------ here
}

and pass data like this:

var userinfo = { name: addedName, email: addedEmail };
data: JSON.stringify(userinfo) 

Also you should see : Posting JavaScript objects with Ajax and ASP.NET MVC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM