简体   繁体   中英

Passing data from dropdownlist in view to controller

We've been searching for like a day right now and we can't figure out to pass data from our view to our controller. In fact we want the user to select an hour from the dropdownlist on the Index() View as StartTime for a time block. At the moment we have to following code.

Our action in the controller

public ActionResult genBlocks(string StartTime, FormCollection collection)
{
    int blocksPerDay = 4;
    int strH, strM;
    List<Block> blocks = new List<Block>();
    for (int i = 0; i < blocksPerDay; i++)
    {
       if (i != 0)
       {
          strH = blocks[i-1].EndTime.Hour;
          strM = blocks[i-1].EndTime.Minute;
       }
       else
       {
          strH = Convert.ToInt32(collection["StartTime"]);
          strM = 0;
        }
        Block block = new Block
        {
            FieldDayId = 1,
            Available = true,
            StartTime = DateTime.Today + new TimeSpan(strH, strM, 0),
            EndTime = DateTime.Today + new TimeSpan(strH, strM + (db.Sports.Find(1).Duration*(i+1)), 0),
        };
        blocks.Add(block);
        db.Blocks.Add(block);
        db.SaveChanges();
    }
    return RedirectToAction("Index");
}

And in our View I implemented a form

@using (Html.BeginForm("genBlocks"))
{
    <input type="text"name="StartTime" />
    @Html.DropDownList("StartTime", String.Empty)

        <div id="genBlocks" class="button">
            <input type="submit" />
        </div>
}

So we tried it with the dorpdownlist and also with a textbox but none of them work out...

Try using following code

Controller - Make sure you put HttpPost attribute there

 [HttpPost]
 public ActionResult genBlocks(string StartTime,FormCollection collection)
 {
   return View();
 }

Your view -- Make sure you put actual action & controller name in beginform method

@using (Html.BeginForm("genBlocks","ControllerName"))
{
    <input type="text" name="StartTime" />

    <div id="genBlocks" class="button">
        <input type="submit" />
    </div>
}
@using (Html.BeginForm("genBlocks", "Block"))
{
@Html.DropDownList("StartTime", String.Empty)
<input type="submit" class="button" value="Generate blocks" />
}

was the solution for the index :)

Your drop down list is really only sending back a single scalar value - the currently selected value. This can be an int, string, whatever. If it's part of your model, you can use Html.DropDownListFor(m => m.Hour, [INSERT POSSIBLE SELECTITEMLIST ARRAY HERE]).

The other option is to simply accept an int, string, etc on your action method if you need to get only that value.

It seems the issue is being over-worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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