How to Use Html.Listboxfor and Html.Beginform

1.5k views Asked by At

I am trying to populate a listbox and parse the selected option back to the controller. Problem is I can't seem to figure out BeginForm and Listboxfor. The tutorials found online only confuse me more.

Here's my csHtml:

@Html.BeginForm("BtnSelectPost", "TimelinePageController")
    {
        <div>
             <select id="s1" class="timeline" size="20" name="Options">
                    @foreach (var C in Model)
                    {
                        Html.ListBoxFor(?)
                    }
             </select>
        </div>
    }

Here's my Controller:

        public List<Contribution> Contriblist = new List<Contribution>();
    // GET: TimelinePage
    public ActionResult TimelinePage(Event Event)
    {        
        Contriblist = DatabaseGetContribution.GetContributions(Event.ID);
        return View(Contriblist);
    }

        public SelectList GetAllContrib()
    {
        SelectList Contribslist = new SelectList(Contriblist, "ID", "Text");
        return Contribslist;
    }

What would I have to do to get it working?

Any help would be great

EDIT: I'm sorry for the lack of information: I'm using 2 models. Contribution:

    public int ID { get; set; }
    public int ContributionID { get; set; }
    public DateTime DateTime { get; set; }    
    public string Category { get; set; }
    public int Likes { get; set; }
    public int Reports { get; set; }    
    public int PostID { get; set; }
    public byte[] File { get; set; }
    public string Attachment { get; set; }
    public Message Message { get; set; }

    /// <summary>
    /// Create Constructor
    /// </summary> 
    /// <param name="category">The category of a post</param>    
    /// <param name="likes">The amount of likes of a post</param> 
    /// <param name="file">The file belonging to the post</param>
    /// <param name="postID">This is the ID of the post reacted to</param>
    public Contribution(DateTime datetime, string category, int likes, int reports, int postid, Message message)
    {           
        this.Category = category;    
        this.Likes = likes;
        this.Reports = reports;
        this.PostID = postid;
        this.DateTime = datetime;
        this.Message = message;
    }

And ViewModelContrib:

public IEnumerable<SelectListItem> contrib { get; set; }

The values in contribution are taken from a database and the Event is only used to take the ID from to check which contributions should be taken from the database.

Thank you all for your help.

2

There are 2 answers

0
Jigarb1992 On

Just for the example for binding data to listview and submit form

First create a Model class and DbContext

    public class Country
    {
        public int CountryId { get; set; }
        public string CountryName { get; set; }

    }

    public class ConuntryContext : DbContext
    {
        public virtual DbSet<Country> Country { get; set; }
    }

Next Create Controller

public class TestController : Controller
    {
        ConuntryContext db = new ConuntryContext();

        public ActionResult Index()
        {
            db.Country.Add(new Country { 
                CountryId = 1,
                CountryName = "India"
            });

            db.Country.Add(new Country
            {
                CountryId = 2,
                CountryName = "USA"
            });

            db.Country.Add(new Country
            {
                CountryId = 3,
                CountryName = "UK"
            });

            db.SaveChanges();

            var countries = db.Country.ToList();
            ViewBag.countries = new SelectList(countries, "CountryId", "CountryName");
            return View();
        }

        [HttpPost]
        public ActionResult Action(Country country)
        {
            var countries = db.Country.ToList();
            ViewBag.countries = new SelectList(countries, "CountryId", "CountryName");
            ViewBag.selectedValue = db.Country.Where(a => a.CountryId == country.CountryId).Select(a => a.CountryName).SingleOrDefault();
            return View();
        }
}

Finally create view

@using (Html.BeginForm("Index", "Test", FormMethod.Post))
{

    @Html.ListBox("CountryId", (SelectList)ViewBag.countries)
    <br/>
    <button type="submit">Submit</button>
}
<p>You have selected @ViewBag.selectedValue Country</p>
6
Mir Gulam Sarwar On

Here is a solution Add property to your class or ViewModel

public IEnumerable<SelectListItem> YourPropertyName{get;set;}

Then in your controller bind the value for list box Then in your view

@Html.BeginForm("BtnSelectPost", "TimelinePageController")
    {
        <div>
             @Html.ListBoxFor(m=>m.ModelPropertyYouWantToBindTo,Model.YourPropertyName)
        </div>
    }

That's it. Listbox now should show the values