简体   繁体   中英

How do I pass a variable from my View to my Controller?

I've generated a <select> dropdown menu on my view page with data from a stored procedure. Using JavaScript, I've accessed the selected <option> and saved the text into a variable. Now I need to send that variable back to my controller so I can use it as a parameter in another stored procedure.

Here is my Controller, titled "EventsController.cs"

    public ActionResult Dropdown(string text)
    {
        ViewData["ids"] = db.uspGetAllEventIds().ToArray();
        Console.WriteLine(text);
        return View();
    }

So you can see I run the 1st stored procedure and send it to the view.

Here's what happens in the view:

@model IEnumerable<Heatmap.Models.Event>
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
    <script>
        function showValue()
        {
            var list = document.getElementById("EventId");
            var text = list.options[list.selectedIndex].text;
            alert(text);    
        }
    </script>
</head>
<body>
    <div>
        @using (Html.BeginForm("", "", FormMethod.Post))
        {
         <select id="EventId">
            @{
                var ids = ViewData["ids"] as string[];
                for (var i = 0; i < ids.Length; i++)
                {
                <option>@ids[i]</option>
                }
              }
         </select>
         <input name="text" type="submit" value="Submit" />
         <button onclick="showValue()">Click me!</button>
        }
    </div>
</body>
</html>

So right now I have this alert function just to prove to myself that I have access to the option that I select. I'm pretty sure I need to use FormMethod.Post to get it back to the Controller, but I haven't been able to find any helpful references so far.

How do I format this so my variable text gets sent back into the controller?

I suggest to use jquery $.getJSON method to send and get variable from controller without refresh the page. I added .NetFiddle it works here

[HttpGet]
public JsonResult GetDropdownList()
{
    var yourdata = db.uspGetAllEventIds().ToList();
    Console.WriteLine(text);
    return Json(new { data = yourdata}, JsonRequestBehavior.AllowGet);
}

[HttpPost]
public ActionResult Dropdown()
{
    // add your code here
}

//html
@using (Html.BeginForm("Dropdown","YourControllerName", FormMethod.Post))
{
    <select id="EventId" name="eventId">
    </select>           
    <input name="text" type="submit" value="Submit" />              
}
<button style="margin-top:20px;" id="yourid">Fill Dropdown!</button>

// jquery
$("#yourid").on("click", function(){
    showValue();
})

function showValue()
{
    $.getJSON('@Url.Action("GetDropdownList", "YourControllerName")', function (result) {

        $("#EventId").html(""); // makes select null before filling process
        var data = result.data;
        for (var i = 0; i < data.length; i++) {
            $("#EventId").append("<option>"+ data[i] +"</option>")
            console.log(data[i])
        }

    })   
}

A better way of doing it is you do a postback to your Dropdown(...) action on button click and change its signature to Dropdown(string EventId) which should give you selected EventId.

Here is the full code using both the methods.

public class EventsController : Controller
    {
        public ActionResult Dropdown()
        {
            ViewData["ids"] = new[] { 1, 2, 3 };
            return View();
        }

        [HttpPost]
        public ActionResult Dropdown(string eventId)
        {
            //call your sp instead of going back to the same page

            ViewData["ids"] = new[] { 1, 2, 3 };
            return View();
        }

        public ActionResult Direct(int id)
        {
            //call your sp instead of going back to the same page

            ViewData["ids"] = new[] { 1, 2, 3 };
            return View("Dropdown");
        }

    }

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
    <script
              src="https://code.jquery.com/jquery-3.2.1.min.js"
              integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
              crossorigin="anonymous"></script>
    <script>
        function showValue() {
            var list = document.getElementById("EventId");
            var text = list.options[list.selectedIndex].text;
            $.getJSON('/Events/Direct/' + text, function(data) {
                console.log(data);
            });
        }
    </script>
</head>
<body>
    <div>
        @using (Html.BeginForm("Dropdown", "Events", FormMethod.Post))
        {
         <select id="EventId" name="eventId">
            @{
                var ids = ViewData["ids"] as int[];
                for (var i = 0; i < ids.Length; i++)
                {
                <option>@ids[i]</option>
                }
              }
         </select>
         <button type="submit">Postback</button>
        }

        <button onclick="showValue()">Get JSON</button>
    </div>
</body>
</html>

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