gpt4 book ai didi

c# - 如何将 Enum int 值传递给 Controller

转载 作者:行者123 更新时间:2023-11-30 21:45:34 24 4
gpt4 key购买 nike

我的模型中有枚举

  public enum Months
{
January = 1,
February = 2,
March = 3,
April = 4,
May = 5,
June = 6,
July = 7,
August = 8,
September = 9,
October = 10,
November = 11,
December = 12
}

显示月份名称的 View

 <div class="left row">
@using (Html.BeginForm("ViewDetails", "Employees", FormMethod.Post))
{
<input type="hidden" id="UserId" name="UserId" value="@ViewBag.UserId" />
<div class="col-sm-4">
<div class="col-sm-6">
@Html.DropDownList("SelMonth", new SelectList(Enum.GetValues(typeof(OSCTrackWeb.Models.AttendanceMaster.Months))), "Select Month", new { @class = "form-control" })
</div>
<div class="col-sm-6">
@Html.DropDownList("SelYear", Enumerable.Range(DateTime.Now.Year, 10).Select(x => new SelectListItem { Text = x.ToString() }), "Select Year", new { @class = "form-control" })
</div>
</div>

<input class="btn btn-primary" type="submit" value="Filter" />
<input class="btn btn-info" type="button" value="Reset" onclick="return Reset();" />

}
</div>

现在我想要从 Controller 中的表单中选择的枚举月份的 int 值

    public ActionResult ViewDetails(int UserId, string currentFilter, int? SelMonth, int? SelYear, string searchString, int? Page_No)
{

int Size_Of_Page = 10;
int No_Of_Page = (Page_No ?? 1);

if (searchString != null)
{
No_Of_Page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;

ViewBag.UserId = UserId;

if (UserId != null)
{
if (SelMonth == null && SelYear == null)
{
SelMonth = DateTime.Now.Month;
SelYear = DateTime.Now.Year;

List<AttendanceMaster> amobj = db.AttendanceMasters.Where(s => s.EmpId == UserId && s.AttendanceDate.Value.Month == SelMonth && s.AttendanceDate.Value.Year == SelYear).ToList();

ViewBag.Name = LoggedUser.Name;
IPagedList<AttendanceMaster> lstdtl = amobj.ToPagedList(No_Of_Page, Size_Of_Page);
return View("ViewDetails", lstdtl);

}
else
{
List<AttendanceMaster> amobj = db.AttendanceMasters.Where(s => s.EmpId == UserId && s.AttendanceDate.Value.Month == SelMonth && s.AttendanceDate.Value.Year == SelYear).ToList();

ViewBag.Name = LoggedUser.Name;
IPagedList<AttendanceMaster> lstdtl = amobj.ToPagedList(No_Of_Page, Size_Of_Page);
return View("ViewDetails", lstdtl);
}
}
else
{
return null;
}

}

那么我怎样才能得到 int 值,比如 1 表示 1 月,6 表示 6 月等等。帮帮我

最佳答案

您可以将您的 Action 签名更新为以下内容:

public ActionResult ViewDetails(int UserId, string currentFilter, OSCTrackWeb.Models.AttendanceMaster.Months SelMonth, int? SelYear, string searchString, int? Page_No)

MVC 会将提交的值绑定(bind)到您的枚举本身。如果未提供任何内容,则 SelMonth 的值将默认为 0(尽管您尚未为 0 定义枚举值)。

如果需要,您可以检查提供的值是否在您的枚举中定义

Enum.IsDefined(typeof(OSCTrackWeb.Models.AttendanceMaster.Months), SelMonth);

关于c# - 如何将 Enum int 值传递给 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39997541/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com