如何从DropDownList中的选定项获取Id - ASP.NET MVC [英] How to get an Id from a selected item in DropDownList - ASP.NET MVC

查看:67
本文介绍了如何从DropDownList中的选定项获取Id - ASP.NET MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。我的数据库上有三个表:



Hi. I have three tables on my database:

Genre(IdGenre, Genre, Description)
Text(IdText, IdUser, Text)
TextGenre(IdTextGenre, IdText(FK), IdGenre(FK)
)





第三张表是连接文本和流派,因为我希望表格文本有2个流派,当我搜索流派时,它会自动显示这种流派的文本。



我的问题是:如何从下拉列表中的选定项目中获取ID?这是我的DropDownList





This third tables is to connect text and genre, because I want the table text to have until 2 genres, and When I search for a genre, automatically it shows the text that are in such genre.

My question is: How do I get an Id from a selected item in dropdownlist? Here is my DropDownList

@Html.DropDownListFor(model => model.IdGenero, ((IEnumerable<AllFiction.Models.Genre>
            )ViewBag.Genres).Select(option => new SelectListItem
            {
            Text = option.Genre,
            Value = option.IdGenre.ToString(),
            Selected = (Model != null) && (Model.IdGenre== option.IdGenre)
            }), "Select a Genre")





这是我创建文本的动作:







And here is my action to create Texts:


[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult CreateText(Text text)
        {
            if (ModelState.IsValid)
            {
               db.Text.Add(text);
           
 TextGenre tg = new TextGenre();
 
               tg.IdText = text.IdText;
               tg.IdGenre = // Here is where i want to put the id of the selected item of the dropdownlist

               db.SaveChanges();
               return RedirectToAction("Index", "User");
            }
               ViewBag.Genres= db.Genre.ToList();
 
            return View(text);
        }





任何人都知道我该怎么做?谢谢!



Anyone know how can I do this? Thanks!

推荐答案

正如您将使用HTML元素一样,您不会直接在控制器代码中使用它。有各种方法可以将HTML元素值传递给控制器​​,这些都在我写的帖子中解释。



请查看它这里 [ ^ ]。



希望这肯定会有所帮助。
As you would be using HTML elements you will not get it directly to use in you controller code. There are various ways to pass the HTML elements value to the controller and those are being explained here in a post written by me.

Please have a look into it here[^].

Hope this will definitely of help.


根据我的信息和经验

如果这是一个post方法那么你的模型对象即(文本文本)应该带来所有选定的字段结果。



你试过吗?????

< br $> b $ b

According to my information and experience
If this is a post method then your Model Object i.e (Text text) should bring all the selected field results.

have you tried it as?????


tg.IdText = text.IdText;
tg.IdGenre = text.IdGenere


这篇关于如何从DropDownList中的选定项获取Id - ASP.NET MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆