简体   繁体   English

mvc5 razor 将参数发送到控制器

[英]mvc5 razor send parameter to controller

I would like to send back a parameter to a controller based on user selection in the view.我想根据视图中的用户选择将参数发送回控制器。

This is what I have in the view:这是我的看法:

@model IEnumerable<Users>

@{
    ViewBag.Title = "FieldSaver Users";
}

<h2>Users</h2>
@foreach(char c in ViewBag.Alphabet)
{
    @Html.ActionLink(c.ToString(), "Home/" + c, new object { }, new { @class = "alphabet", @letter = c })
}
    <div class="table-responsive">
        <table class="table table-striped">
            <tr>
                <td>Username</td>
                <td>First name</td>
                <td>Last name</td>
            </tr>
            @foreach (var user in Model)
            {
                <tr>
                    <td>@user.UserName</td>
                    <td>@user.FirstName</td>
                    <td>@user.LastName</td>
                </tr>
            }
        </table>
    </div>

And this is the controller:这是控制器:

   public ActionResult Home(string letter)
            {
                ViewBag.Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                using (var db = new App.Models.DbContext())
                {
                    List<Users> users = (from p in db.Users
                        select p).ToList();
                    return View(users);
                }
                return View();
            }

So, when someone will click on a letter in the alphabet links, I want to send back the value to the controller, currently the postback is happening but the letter parameter is null.因此,当有人单击字母链接中的字母时,我想将该值发送回控制器,目前正在回发,但字母参数为空。

What am I doing wrong?我究竟做错了什么?

What you're currently using as new object { } is where you provide the route data.您当前使用的new object { }是您提供路线数据的地方。 You're adding it as an HTML attribute.您将其添加为 HTML 属性。

In your case, it should be like this:在你的情况下,它应该是这样的:

@Html.ActionLink(c.ToString(),
    "Home", 
    new { letter = c }, 
    new { @class = "alphabet" })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM