Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi. I have three tables on my database:

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


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!
Posted
Updated 13-Oct-14 17:14pm
v2
Comments
NowYouSeeMe 13-Oct-14 23:40pm    
instead of creating a model object inside.pass the the model from view to controller using Ajax.BeginForm() or Html.BeginForm()

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.
 
Share this answer
 
Comments
Member 11126363 15-Oct-14 0:14am    
Thanks Man!! That's what I needed. thanks a lot.
SRS(The Coder) 15-Oct-14 0:51am    
Welcome Always :)
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?????


C#
tg.IdText = text.IdText;
tg.IdGenre = text.IdGenere
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900