【问题标题】:Passing data from dropdownlist in view to controller将视图中的下拉列表中的数据传递给控制器
【发布时间】:2012-05-21 11:06:40
【问题描述】:

我们现在已经搜索了一天,但我们无法将数据从我们的视图传递到我们的控制器。事实上,我们希望用户从 Index() 视图的下拉列表中选择一个小时作为时间块的 StartTime。目前我们必须遵循代码。

我们在控制器中的操作

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");
}

在我们的视图中我实现了一个表单

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

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

所以我们使用 dorpdownlist 和文本框进行了尝试,但都没有成功...

【问题讨论】:

标签: c# asp.net-mvc asp.net-mvc-3 view controller


【解决方案1】:

尝试使用以下代码

控制器 - 确保将 HttpPost 属性放在那里

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

你的观点——确保你把实际的动作和控制器名称放在 beginform 方法中

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

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

【讨论】:

  • 感谢您的回答,但它还不起作用,请问您为什么要在其中输入“测试”?
  • 你用你的控制器名称替换那个测试
【解决方案2】:
@using (Html.BeginForm("genBlocks", "Block"))
{
@Html.DropDownList("StartTime", String.Empty)
<input type="submit" class="button" value="Generate blocks" />
}

是索引的解决方案:)

【讨论】:

    【解决方案3】:

    您的下拉列表实际上只发回一个标量值 - 当前选定的值。这可以是一个 int、string 等等。如果它是您模型的一部分,您可以使用 Html.DropDownListFor(m => m.Hour, [INSERT POSSIBLE SELECTITEMLIST ARRAY HERE])。

    如果您只需要获取该值,则另一种选择是在您的操作方法上简单地接受 int、string 等。

    看来这个问题被过度处理了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多