Search code examples
htmlasp.net-corerazor

How can get value of an item based on ID in cshtml?


Let says I have a select tag with a specific id and multiples option. Then below, I want to display partial view base on the selected . I think of using something as if else statement but I don't know how to gain the value of that select with c#.

My thought about this is like this

    <select id="selectItem">
        <option value="A">A</option>
        <option value="B">A</option>
        <option value="C">A</option>
    </select>
    
    @if ('selectItem' == "A"){
        <partial name="..."/>
    }

Solution

  • you can do it with js,here is a demo: Controller(Test):

    public IActionResult Index()
            {
                return View();
            }
            public IActionResult Partial()
            {
                return PartialView("Partial1");
            }
    

    Partial1:

        <h1>Partial1</h1>
    Index.cshtml:
    <select id="selectItem">
        <option value="A">A</option>
        <option value="B">B</option>
        <option value="C">C</option>
    </select>
    <div id="PartialContent"></div>
    

    js:

    <script>
            $(function () {
                getPartial();
            });
            $("#selectItem").change(function () {
                getPartial();
            });
            function getPartial() {
                if ($("#selectItem").val() == "C") {
                    $.ajax({
                        type: 'GET',
                        url: "/Test/Partial",
                        dataType: 'html', //dataType - html
                        success: function (result) {
                            //Create a Div around the Partial View and fill the result
                            $('#PartialContent').html(result);
                        }
                    });
                }else {
                         $('#PartialContent').html("");
                 }
            }
        </script>
    

    result: enter image description here