MVC5如何从用户写入复选框值

时间:2016-05-19 20:58:43

标签: c# asp.net-mvc

好的,所以我拿到了我的复选框,我有我的选项,如果我选择任何一个,我想写下提交的所选项目的价值,听起来很容易吗?好吧,每当我点击任何选项并提交它时,该值都显示在URL上,但我似乎无法将其写出来......

查看(Index.cshtml):

@using vgsimulator.Models
@model List<vgsimulator.Models.Album>
@{
    ViewBag.Title = "Index";
    Album ka = new Album();
}

@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
    for (var i = 0; i < Model.Count(); i++)
    {
        @Html.HiddenFor(it => it[i].Id)
        @Html.DisplayFor(it => it[i].Name)
        @Html.CheckBoxFor(it => it[i].Checked)
    }
    <input id="Submit1" type="submit" value="submit"/>
    <p>@Viewbag.Values</p> //here we print values checked
}

模型(Album.cs):

public class Album
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Checked { get; set; }
}

控制器(HomeController.cs):

[HttpGet]
public ActionResult Index()
{
    var list = new List<Album>
    {
        new Album { Id = 1, Name = "Aquafina", Checked = false },
        new Album { Id = 2, Name = "Mulshi Springs", Checked = false },
        new Album { Id = 3, Name = "Alfa Blue", Checked = false },
        .....
    };
    return View(list);
}


[HttpPost]
public ActionResult Index(List<Album> list)
{
    //ViewBag.Values = x?;
    return this.View(list);
}

1 个答案:

答案 0 :(得分:0)

如果要在post方法中返回时在视图中显示所选值,请先为@Html.HiddenFor(m=> m[i].Name) 属性添加隐藏输入,以便回发

[HttpPost]
public ActionResult Index(List<Album> list)
{
    var selected = list.Where(x => x.Checked).Select(x => x.Name);
    ViewBag.Values = String.Join(", ", selected );
    return View(list);
}

然后将POST方法修改为

Album

将显示<p>元素中所有选定Album的逗号分隔列表。

当然,这个UI毫无意义,但是从评论开始,它只是一个能够获取所选项目的测试,然后再编写代码来保存它们。假设您希望为应用的用户存储所选的UserAlbums集合,您可能会有一个表(例如)UserId,其中包含AlbumId[HttpPost] public ActionResult Index(List<Album> list) { var userId = ....; // get the ID of the current user IEnumerable<int> selected = list.Where(x => x.Checked).Select(x => x.Id); foreach(int id in selected) { db.Add(new UserAlbum() { UserId = userId, AlbumId = id }); } db.SaveChanges(); return RedirectToAction(...); // redirect to another view } 的字段,然后保存所选项目,你会使用类似

的东西
{{1}}