简体   繁体   中英

Populate a textbox based on selected value from dropdown using ASP.NET Core MVC

I am using ASP.NET Core 3.1 MVC to create a page with a form. The form has a dropdown and a textbox. The dropdown is populated with values from the database. The textbox will populate with a value from the same table and the dropdown, based on the selected dropdown value. My goal is to call a function from my controller inside of my view, is that possible?

My cshtml file:

<form method="post" asp-controller="Index" asp-action="Index" role="form">
<div class="form-group">
<select id="fileName" asp-items="@(new SelectList(ViewBag.message, "ID", "fileName"))" onchange="getUploadedFile()"></select>
<input />
</div>
</form>

My Model

public class myFiles
{
public int ID {get; set;}
public string fileName {get; set;}
public string uploadedFile {get; set;}
}

My controller has a function named GetUploadedFile() which runs a query to the database that returns the file name based on the ID. I originally thought I could reference the GetUploadedFile through my view(cshtml file) by adding the onchange handler and setting it as onchange="GetUploadedFile()". I have also tried to do an ajax call to get the UploadedFile.

My goal is to call a function from my controller inside of my view, is that possible?

Do you mean you want to add the myfiles' uploadfile value according to the dropdownlist selected value in the onchange getUploadedFile jquery method? If this is your requirement, I suggest you could try to use ajax to achieve your requirement.

You could write the ajax to post request to the mvc action, then you could get the value and set the result to the textbox.

Details, you could refer to below codes:

<form method="post" asp-controller="home" asp-action="Index" role="form">
    <div class="form-group">
        <input id="uploadedFile" type="text" class="form-control" />
        <select id="fileName" asp-items="@(new SelectList(ViewBag.message, "ID", "fileName"))" onchange="getUploadedFile(this)"></select>
    </div>
</form>

<script>
    function getUploadedFile(Sle) { 
        $.ajax({
            url: "/Home/GetUploadfileName",
            data: { "FileID": Sle.value} ,
            type: "Post",
            dataType: "text",
            success: function (data) {
                console.log(data);
                $("#uploadedFile").val(data);

            },
            error: function (data) {
                alert(data);
            }
        });
    }
</script>

Action method:

    private List<myFiles> myfiletestdata = new List<myFiles>() {
         new  myFiles(){ ID=1, fileName="test1", uploadedFile="testuploadfile" },
         new  myFiles(){ ID=2, fileName="test2", uploadedFile="testuploadfile2" },
            new  myFiles(){ ID=3, fileName="test3", uploadedFile="testuploadfile3" },
        };

    [HttpPost]
    public IActionResult GetUploadfileName(int FileID) {

        //get the filename result accoding to ID

         
        var result = myfiletestdata.Where(x=>x.ID== FileID).First();


        return Ok(result.uploadedFile);
    
    }

Result:

在此处输入图像描述

If I understand correctly, you just want to get the file name from the database when a value from the dropdown is selected.

What errors did you get when you tried the ajax call??

In your cshtml file, you can have something like this:

    <script>

        function getUploadedFile() {
            var id = $('#fileName option:selected').val();
            
            $.getJSON('/ControllerName/GetUploadedFile', { id: id }, function (result) {
                var file = result.fileName;
                .... do whatever with the result

                to set value of the textbox:

                 $('#textBoxId').text(file);
            });
        }

    </script>

Instead of getJSON, you could use ajax:

    <script>

        function getUploadedFile() {
            var id = $('#fileName option:selected').val();
            
            $.ajax({
                url: 'ControllerName/GetUploadedFile',
                type: 'GET',
                dataType: 'json',
                data: {
                    'id': id 
                }
            })
            .done(function (result) {
                if (!result.errored) {
                    var file = result.fileName;
                }
                else {

                }
            });
        }

    </script>

Then in your controller, if you are not submitting the form and just want to update the value of the textbox, then it can just be:

        [HttpGet]
        public async Task<IActionResult> GetUploadedFile(int id)
        {
            Sample code:

            var file = await GetFileFromDb(id);

            return Json(new { fileName = file });
        }

Also, you should consider using ViewModels instead of ViewBag.

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