简体   繁体   中英

How to fill a textbox from database when dropdownlist's selected item changed in ASP.NET MVC

I am new to MVC and Javascript. I am trying to make a "change user info" page for admin. I have a dropdown which lists registered users and some textbox for enter various info about users (eg, name, surname). My objective is auto fill textboxes with users current info when selected an user with dropdownlist. But because of MVC is not event driven and doesn't have postback I don't exactly know how to accomplish this. I think I have to trigger a controller method by dropdownlist's onchange and I think the only way is using JS, AJAX or something like these.

Note: I can do all database stuff in Controller.

I have this code so far in my view:

.... @Html.DropDownList("Users", ViewBag.Users as SelectList, "Select a User", new {  id="UserId", onchange="userChanged()"} ) ....





.... <script type="text/javascript">

function userChanged() {

 } 

</script> ....
$(document).ready(function(){
        $("#UserId").change(function () {
        if ($(this).val() != "" && $(this).val() != undefined && $(this).val() != null)
            $.ajax({
                type: "GET",
                url: "/[ControllerName]/[ActionName]/" + $("#UserId").val()
            })
            .success(function (data) {
                // 'data' consits of values returned from controller.
                // fill textboxes with values in 'data'
            });
    });
});

Hope this helps you.

Try something like this (fiddle) :

<select id="select1">
    <option value="userId1">User 1</option>
    <option value="userId2">User 2</option>
    <option value="userId3">User 2</option>
</select>

<textarea id="txt1">
</textarea>

$(function(){
    $('#select1').change(function(){
        $.ajax({
            url: "YourAction", // Url.Action()
            data: {
                userId: $(this).val()
            },
            success: function(data) {
                $('#txt1').val(data);
            }
        });
    });
});

You can define your controller action method as JsonResult and call it from your jquery using AJAX. Once you get data using AJAX, you can parse it and fill appropriate textbox with that data. you can use below code on how to call ajax in you userChanged method:

$.ajax ({
 url: '/Controller/Action',
 type: 'GET',
 async: true,
 cache: false,
 data: { userId: useridofwhichdatatobefetched},
 success: function (result) {
  $("#usernametextbox").val = result.userName; }
});

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