3

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.

3
  • any update? Does my reply answer your questions? Jun 30, 2020 at 2:18
  • @BrandoZhang Hello, thanks for your response! Yes, your answer helped a ton. Thanks so much.
    – Kya Clark
    Jul 1, 2020 at 19:23
  • If my answer has helped you to solve the issue, please mark it as answer, so that other folks who faces the same issue will find the solution more easily. Thank you. Jul 2, 2020 at 0:16

2 Answers 2

2

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:

enter image description here

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.