简体   繁体   中英

javascript or ajax to update database with asp.net mvc?

I have a function here from a change event on a dropdownlist. When the selection gets changed I want to update a row in my database. Should I use javascript or ajax. I don't want the page to be refreshed. I think it should be ajax, but not sure? If ajax, can anyone point me to a tutorial/video/etc?

Here is where I want to update my db row.

var statusdropdown = document.getElementById("enumstatus");
statusdropdown.addEventListener("change", function(event) {
    // call db and update row
}, false);

Looks like you using asp.net mvc.

You can write your ajax calls with pure javascript Ajax docs or the easiest way, using JQuery .

You need to add one action on your controller to receive the ajax data, and then insert/update your db.

See this , this and this .

Most common scenario would be making an ajax call using HTTP POST/PUT to a controller method, which would then handle the data and update the database directly or pass through to your service/data layer code.

Probably the easiest way to make the call would be using the jQuery.ajax method. Documentation can be found here: http://api.jquery.com/jquery.ajax/

You can try something like this

<script type="text/javascript">
    $(function () {
        $('#btnSubmit').click(function () {
            var name = $('#TextBox1').val();
            var email = $('#TextBox2').val();
            if (name != '' && email != '') {
                $.ajax
                    ({
                        type: 'POST',
                        url: 'Home/UpdateDB',     //if it is plain asp.net then UpdateDB is declared as WebMethod 
                        async: false,
                        data: "{'name':'" + name + "','email':'" + email + "'}",
                        contentType: 'application/json; charset =utf-8',
                        success: function (data) {
                            var obj = data.d;
                            if (obj == 'true') {
                                $('#TextBox1').val('');
                                $('#TextBox2').val('');
                                alert("Data Saved Successfully");
                            }
                        },
                        error: function (result) {
                            alert("Error Occured, Try Again");
                        }
                    });
            }
        })
    });
</script> 
  • fg
  • iuou
  • uouienter link description here
  • uiouidfgs dfgd dfgdfgdfgdgdgd##


















Heading


##*

  • uio
  • uiopomkl
  • hjlkdsg
  • dsf
  • dfgdg

Blockquote

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