从视图到控制器获取开始日期和结束日期值,而不使用模型

时间:2015-05-28 07:42:25

标签: asp.net-mvc razor

我有一个视图,其中包含两个字段的开始日期,类型日期的结束日期和按钮单击控制器返回集合上的按钮。 和I Enumerable类型的模型。 我想在控制器中获取开始日期和结束日期值并处理我的东西并返回到相同的视图并使用foreach循环显示所有集合

这是我的观点

<button onclick="window.location.href=""></button>

和模型

@model IEnumerable<EChallan.DataModel.CustomModel.OffenceCodeByDateCM>

@{
    ViewBag.Title = "OffenceCodeByDate";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2 style="color:White">Offence Code By Date</h2>
<div style="text-align: center; width: 100%;">


    <table>
        @using (Html.BeginForm("OffenceCodeByDate", "Report", FormMethod.Post))
        {

             @*@String.Format("{0:dd-MMMM-yyyy}", item.Documentdate)*@        
            <tr>
                <td>

                    <span class="login-text">Star Date:</span> <span class="inpt-css">
                </td>
                @*<td> @Html.TextBoxFor(model => model.NAME, new { @required = "true" })</td>*@
                <td>
                @Html.TextBoxFor(model => model.StartDate, new { @required = "true", type = "date" , value="startdate" })
                </td>



                <td> <button id="btnsubmit" type="submit" name="Report" class="btn btn-large btn-info pull-right">Report </button>
                </td>
            </tr>
        }
    </table>
</div>

2 个答案:

答案 0 :(得分:2)

首先创建一个包含日期和集合属性的视图模型

public class OffenceCodeVM
{
  public DateTime StartDate { get; set; }
  public DateTime EndDate { get; set; }
  public IEnumerable<OffenceCodeByDateCM> Items { get; set; }
}

然后在控制器GET方法

public ActionResult Index(DateTime startDate, DateTime endDate)
{
  OffenceCodeVM model = new OffenceCodeVM()
  {
    StartDate = startDate,
    EndDate = endDate,
    Items = // populate this from the database based on the method parameters
  };
  return View(model);
}

然后在视图中

@model yourAssembly.OffenceCodeVM
@using (Html.BeginForm("OffenceCodeByDate", "Report", FormMethod.Get)) // note the FormMethod.Get
{
  @Html.TextBoxFor(m => m.StartDate)
  @Html.TextBoxFor(m => m.EndDate)
  <input type="submit" .../>
}
@foreach(var item in Model.Items)
{
  .... // render the elements to display your properties of each OffenceCodeByDateCM object
}

作为替代方案,您可能需要考虑使用ajax将日期传递给另一个方法,该方法返回&#39;报告的部分视图。它将提高性能,因为只需要更新部分视图。

答案 1 :(得分:0)

您可以在不使用下面的模型的情况下将值传递给控制器​​

@using (Html.BeginForm("OffenceCodeByDate", "Report", FormMethod.Post))
{
      @Html.TextBoxFor(model => model.StartDate, new { @required = "true", type = "date" , value="startdate" })
}

在控制器中:

[HttpPost]
public ActionResult OffenceCodeByDate(string StartDate)
{
      return View();
}