如何在 asp.net mvc 中用日期填充 html 字段?
How do i fill the html field with date in asp.net mvc?
我正在构建一个 Todo 列表应用程序
型号classTodo.cs如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Todo_Application.Models
{
public class Todo
{
[Display(Name ="Item Id")]
[Required]
public int ItemId { get; set; }
[Display(Name ="Description")]
[Required(ErrorMessage ="Description is required")]
[StringLength(100,MinimumLength =10)]
public string Description { get; set; }
[Display(Name = "Start Date")]
[Required(ErrorMessage ="Start date is required")]
public DateTime StartDate { get; set; }
[Display(Name = "End Date")]
[Required(ErrorMessage ="End date is required")]
public DateTime EndDate { get; set; }
[Display(Name = "Status of completion")]
public Status StatusOfCompletion { get; set; }
public class SortByStartDate : IComparer<Todo>
{
public int Compare(Todo x, Todo y)
{
return x.StartDate.CompareTo(y.StartDate);
}
}
public class SortByEndDate:IComparer<Todo>
{
public int Compare(Todo x,Todo y)
{
return x.EndDate.CompareTo(y.EndDate);
}
}
}
}
我有一个带索引的家庭控制器,添加和编辑操作如下。
public class HomeController : Controller
{
public static List<Todo> ListOfTodos = new List<Todo>()
{
new Todo()
{
ItemId=101,
Description="Plan the module",
StartDate=DateTime.Now,
EndDate=DateTime.Now.AddDays(4),
StatusOfCompletion=Status.YetToStart},
new Todo()
{
ItemId=102,
Description="Dry run the plan",
StartDate=DateTime.Now.AddDays(3),
EndDate=DateTime.Now.AddDays(5),
StatusOfCompletion=Status.YetToStart
}
};
public ActionResult Index()
{
return View(ListOfTodos);
}
static int max = 0;
void maxid()
{
foreach (var v in ListOfTodos)
max = Math.Max(max, v.ItemId);
}
public ActionResult Add()
{
maxid();
Session["id"]= max;
return View();
}
[HttpPost]
public ActionResult Add(Todo t)
{
//if(!ModelState.IsValidField("ItemId"))
//{
// ModelState.AddModelError("ItemId", "invalid id");
//}
//if(string.IsNullOrEmpty(t.Description))
//{
// ModelState.AddModelError("Description", "Description field is empty");
//}
//if (!ModelState.IsValidField("StartDate"))
// ModelState.AddModelError("StartDate", "invalid start date");
//if (!ModelState.IsValidField("EndDate"))
// ModelState.AddModelError("EndDate", "invalid end date");
//if (!ModelState.IsValidField("StatusOfCompletion"))
// ModelState.AddModelError("StatusOfCompletion", "invalid status");
if(ModelState.IsValid)
{
ListOfTodos.Add(t);
return View("Index", ListOfTodos);
}
//ModelState.AddModelError("", "Invalid data");
return View();
}
public ActionResult Delete(int id)
{
ListOfTodos.Remove(ListOfTodos.Find(m => m.ItemId == id));
return View("Index",ListOfTodos);
}
public ActionResult Edit(int id)
{
Todo t = ListOfTodos.Find(m => m.ItemId == id);
return View(t);
}
[HttpPost]
public ActionResult Edit(Todo t1)
{
if (ModelState.IsValid)
{
Todo t = ListOfTodos.Find(m => m.ItemId == t1.ItemId);
t.ItemId = t1.ItemId;
t.Description = t1.Description;
t.StartDate = t1.StartDate;
t.EndDate = t1.EndDate;
t.StatusOfCompletion = t1.StatusOfCompletion;
return View("Index", ListOfTodos);
}
return View();
}
[HttpPost]
public ActionResult SortBy(string Sortby)
{
Todo t = new Todo();
if (Sortby.Equals("Start Date"))
ListOfTodos.Sort(new Todo.SortByStartDate());
else if (Sortby.Equals("End Date"))
ListOfTodos.Sort(new Todo.SortByEndDate());
return View("Index", ListOfTodos);
}
}
还有如下观点:
Index.cshtml
@model IEnumerable<Todo_Application.Models.Todo>
@{
ViewBag.Title = "Index";
int count = 0;
}
<h2>List of todo items</h2>
<a href="/home/add" class="btn btn-primary">Add New Item</a>
<form method="post" action="/Home/SortBy">
Sort By @Html.DropDownList("Sortby", new SelectList(new List<string>() { "Start Date", "End Date" }),
new { htmlAttributes = new {@class = "form-control"}})
<input type="submit" value="Go" class="btn btn-primary" />
</form>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Serial No</th>
<th>Item Id</th>
<th>Description</th>
<th>Start Date</th>
<th>End Date</th>
<th>Completion Status</th>
</tr>
</thead>
<tbody>
@{
foreach(var v in Model)
{
<tr>
<td>
@(count=count+1)
</td>
<td>
@v.ItemId
</td>
<td>
@v.Description
</td>
<td>
@v.StartDate.ToShortDateString()
</td>
<td>
@v.EndDate.ToShortDateString()
</td>
<td>
@v.StatusOfCompletion
</td>
<td>
@Html.ActionLink("edit", "Edit", new { id = v.ItemId })
</td>
<td>
@Html.ActionLink("delete", "Delete", new { id = v.ItemId })
</td>
</tr>
}
}
</tbody>
</table>
和Edit.cshtml如下
@model Todo_Application.Models.Todo
@{
ViewBag.Title = "Edit";
}
<h2>Edit Item</h2>
@using (Html.BeginForm("Edit", "Home", FormMethod.Post))
{
<div class="col-sm-3">
<div class="form-group">
@Html.EditorFor(m => m.ItemId,
new { htmlAttributes = new {@class = "form-control",type="hidden"} })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Description)
@Html.EditorFor(m => m.Description,
new { htmlAttributes = new { @class = "form-control"} })
@Html.ValidationMessageFor(m=>m.Description)
</div>
<div class="form-group">
@Html.LabelFor(m => m.StartDate)
@Html.EditorFor(m => m.StartDate,
new { htmlattributes = new { @class = "form-control datepicker",
type="date" } })
@Html.ValidationMessageFor(m=>m.StartDate)
</div>
<div class="form-group">
@Html.LabelFor(m => m.EndDate)
@Html.EditorFor(m => m.EndDate,
new { htmlattributes = new { @class = "form-control datepicker",
type="date"} })
@Html.ValidationMessageFor(m=>m.EndDate)
</div>
<div class="form-group">
@Html.LabelFor(m => m.StatusOfCompletion)
@Html.EnumDropDownListFor(m => m.StatusOfCompletion,
new { htmlattributes = new { @class = "form-control" } })
</div>
<input type="submit" value="Update" class="btn btn-primary" />
</div>
}
索引视图仅显示所有项目。
编辑视图用于更新项目详细信息。
当我单击编辑 link 时,我需要编辑视图但不会填充日期字段。它填充描述字段。
如何填充日期字段?
更新:
在家庭控制器中,我定义了一个包含 Todo 类型值的列表。开始日期将是今天的日期和时间。当我在索引页上显示时,我只想显示日期,我可以使用 ToShortDateString() 来显示日期。现在当我点击编辑时,只有日期应该被填充而不是时间。最初我使用了一个文本框,所以它用于显示日期和时间。后来,我添加了 datepicker class ,现在没有填充任何内容,而是显示格式 dd/mm/yyyy。
If you want to display the default datetime meanwhile can choose the
datetime, razor doesn't support that. If you want to display date
while loading the edit page in that case it should be type of
string
in that case it will be like textbox. If you want that as
date picker
I think in that case we should change the text
to date picker
. Here is the working demo for you which may you are wanted to implement.
型号:
public class Todo
{
[Display(Name ="Item Id")]
[Required]
public int ItemId { get; set; }
[Display(Name ="Description")]
[Required(ErrorMessage ="Description is required")]
[StringLength(100,MinimumLength =10)]
public string Description { get; set; }
[Display(Name = "Start Date")]
[Required(ErrorMessage ="Start date is required")]
public DateTime StartDate { get; set; }
[Display(Name = "End Date")]
[Required(ErrorMessage ="End date is required")]
public DateTime EndDate { get; set; }
[Display(Name = "Text To Date Picker")]
public Nullable<DateTime> TestDate { get; set; }
}
查看:
@model DotNet6MVCWebApp.Models.Todo
@{
ViewBag.Title = "Edit";
}
<h2>Edit Item</h2>
@using (Html.BeginForm("Edit", "Todo", FormMethod.Post))
{
<div class="col-sm-3">
<div class="form-group">
@Html.EditorFor(m => m.ItemId,
new { htmlAttributes = new {@class = "form-control",type="hidden"} })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Description)
@Html.EditorFor(m => m.Description,
new { htmlAttributes = new { @class = "form-control"} })
@Html.ValidationMessageFor(m=>m.Description)
</div>
<div class="form-group">
@Html.LabelFor(m => m.StartDate)
@Html.EditorFor(m => m.StartDate,
new { htmlattributes = new { @class = "form-control datepicker",
type="date" } })
@Html.ValidationMessageFor(m=>m.StartDate)
</div>
<div class="form-group">
@Html.LabelFor(m => m.EndDate)
@Html.EditorFor(m => m.EndDate,
new { htmlattributes = new { @class = "form-control datepicker",
type="date"} })
@Html.ValidationMessageFor(m=>m.EndDate)
</div>
<div class="form-group">
@Html.LabelFor(m => m.TestDate)
@Html.TextBoxFor(model => model.TestDate, "{0:d/M/yyyy}",new { id="textTodate", @class = "form-control", type = "text" })
</div>
<input type="submit" value="Update" class="btn btn-primary" />
</div>
}
脚本:
@section scripts {
<script>
$(document).ready(function () {
$("#textTodate").click(function (e) {
$("#textTodate").prop('type','date');
});
});
</script>
}
Note: This is loading with the existing date
. While user clicking it to modify I am changing it from textbox
to date picker
by its click event
输出:
希望以上步骤能相应地指导您。
我正在构建一个 Todo 列表应用程序
型号classTodo.cs如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace Todo_Application.Models
{
public class Todo
{
[Display(Name ="Item Id")]
[Required]
public int ItemId { get; set; }
[Display(Name ="Description")]
[Required(ErrorMessage ="Description is required")]
[StringLength(100,MinimumLength =10)]
public string Description { get; set; }
[Display(Name = "Start Date")]
[Required(ErrorMessage ="Start date is required")]
public DateTime StartDate { get; set; }
[Display(Name = "End Date")]
[Required(ErrorMessage ="End date is required")]
public DateTime EndDate { get; set; }
[Display(Name = "Status of completion")]
public Status StatusOfCompletion { get; set; }
public class SortByStartDate : IComparer<Todo>
{
public int Compare(Todo x, Todo y)
{
return x.StartDate.CompareTo(y.StartDate);
}
}
public class SortByEndDate:IComparer<Todo>
{
public int Compare(Todo x,Todo y)
{
return x.EndDate.CompareTo(y.EndDate);
}
}
}
}
我有一个带索引的家庭控制器,添加和编辑操作如下。
public class HomeController : Controller
{
public static List<Todo> ListOfTodos = new List<Todo>()
{
new Todo()
{
ItemId=101,
Description="Plan the module",
StartDate=DateTime.Now,
EndDate=DateTime.Now.AddDays(4),
StatusOfCompletion=Status.YetToStart},
new Todo()
{
ItemId=102,
Description="Dry run the plan",
StartDate=DateTime.Now.AddDays(3),
EndDate=DateTime.Now.AddDays(5),
StatusOfCompletion=Status.YetToStart
}
};
public ActionResult Index()
{
return View(ListOfTodos);
}
static int max = 0;
void maxid()
{
foreach (var v in ListOfTodos)
max = Math.Max(max, v.ItemId);
}
public ActionResult Add()
{
maxid();
Session["id"]= max;
return View();
}
[HttpPost]
public ActionResult Add(Todo t)
{
//if(!ModelState.IsValidField("ItemId"))
//{
// ModelState.AddModelError("ItemId", "invalid id");
//}
//if(string.IsNullOrEmpty(t.Description))
//{
// ModelState.AddModelError("Description", "Description field is empty");
//}
//if (!ModelState.IsValidField("StartDate"))
// ModelState.AddModelError("StartDate", "invalid start date");
//if (!ModelState.IsValidField("EndDate"))
// ModelState.AddModelError("EndDate", "invalid end date");
//if (!ModelState.IsValidField("StatusOfCompletion"))
// ModelState.AddModelError("StatusOfCompletion", "invalid status");
if(ModelState.IsValid)
{
ListOfTodos.Add(t);
return View("Index", ListOfTodos);
}
//ModelState.AddModelError("", "Invalid data");
return View();
}
public ActionResult Delete(int id)
{
ListOfTodos.Remove(ListOfTodos.Find(m => m.ItemId == id));
return View("Index",ListOfTodos);
}
public ActionResult Edit(int id)
{
Todo t = ListOfTodos.Find(m => m.ItemId == id);
return View(t);
}
[HttpPost]
public ActionResult Edit(Todo t1)
{
if (ModelState.IsValid)
{
Todo t = ListOfTodos.Find(m => m.ItemId == t1.ItemId);
t.ItemId = t1.ItemId;
t.Description = t1.Description;
t.StartDate = t1.StartDate;
t.EndDate = t1.EndDate;
t.StatusOfCompletion = t1.StatusOfCompletion;
return View("Index", ListOfTodos);
}
return View();
}
[HttpPost]
public ActionResult SortBy(string Sortby)
{
Todo t = new Todo();
if (Sortby.Equals("Start Date"))
ListOfTodos.Sort(new Todo.SortByStartDate());
else if (Sortby.Equals("End Date"))
ListOfTodos.Sort(new Todo.SortByEndDate());
return View("Index", ListOfTodos);
}
}
还有如下观点: Index.cshtml
@model IEnumerable<Todo_Application.Models.Todo>
@{
ViewBag.Title = "Index";
int count = 0;
}
<h2>List of todo items</h2>
<a href="/home/add" class="btn btn-primary">Add New Item</a>
<form method="post" action="/Home/SortBy">
Sort By @Html.DropDownList("Sortby", new SelectList(new List<string>() { "Start Date", "End Date" }),
new { htmlAttributes = new {@class = "form-control"}})
<input type="submit" value="Go" class="btn btn-primary" />
</form>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Serial No</th>
<th>Item Id</th>
<th>Description</th>
<th>Start Date</th>
<th>End Date</th>
<th>Completion Status</th>
</tr>
</thead>
<tbody>
@{
foreach(var v in Model)
{
<tr>
<td>
@(count=count+1)
</td>
<td>
@v.ItemId
</td>
<td>
@v.Description
</td>
<td>
@v.StartDate.ToShortDateString()
</td>
<td>
@v.EndDate.ToShortDateString()
</td>
<td>
@v.StatusOfCompletion
</td>
<td>
@Html.ActionLink("edit", "Edit", new { id = v.ItemId })
</td>
<td>
@Html.ActionLink("delete", "Delete", new { id = v.ItemId })
</td>
</tr>
}
}
</tbody>
</table>
和Edit.cshtml如下
@model Todo_Application.Models.Todo
@{
ViewBag.Title = "Edit";
}
<h2>Edit Item</h2>
@using (Html.BeginForm("Edit", "Home", FormMethod.Post))
{
<div class="col-sm-3">
<div class="form-group">
@Html.EditorFor(m => m.ItemId,
new { htmlAttributes = new {@class = "form-control",type="hidden"} })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Description)
@Html.EditorFor(m => m.Description,
new { htmlAttributes = new { @class = "form-control"} })
@Html.ValidationMessageFor(m=>m.Description)
</div>
<div class="form-group">
@Html.LabelFor(m => m.StartDate)
@Html.EditorFor(m => m.StartDate,
new { htmlattributes = new { @class = "form-control datepicker",
type="date" } })
@Html.ValidationMessageFor(m=>m.StartDate)
</div>
<div class="form-group">
@Html.LabelFor(m => m.EndDate)
@Html.EditorFor(m => m.EndDate,
new { htmlattributes = new { @class = "form-control datepicker",
type="date"} })
@Html.ValidationMessageFor(m=>m.EndDate)
</div>
<div class="form-group">
@Html.LabelFor(m => m.StatusOfCompletion)
@Html.EnumDropDownListFor(m => m.StatusOfCompletion,
new { htmlattributes = new { @class = "form-control" } })
</div>
<input type="submit" value="Update" class="btn btn-primary" />
</div>
}
索引视图仅显示所有项目。 编辑视图用于更新项目详细信息。 当我单击编辑 link 时,我需要编辑视图但不会填充日期字段。它填充描述字段。 如何填充日期字段?
更新: 在家庭控制器中,我定义了一个包含 Todo 类型值的列表。开始日期将是今天的日期和时间。当我在索引页上显示时,我只想显示日期,我可以使用 ToShortDateString() 来显示日期。现在当我点击编辑时,只有日期应该被填充而不是时间。最初我使用了一个文本框,所以它用于显示日期和时间。后来,我添加了 datepicker class ,现在没有填充任何内容,而是显示格式 dd/mm/yyyy。
If you want to display the default datetime meanwhile can choose the datetime, razor doesn't support that. If you want to display
date
while loading the edit page in that case it should be type ofstring
in that case it will be like textbox. If you want that asdate picker
I think in that case we should change thetext
todate picker
. Here is the working demo for you which may you are wanted to implement.
型号:
public class Todo
{
[Display(Name ="Item Id")]
[Required]
public int ItemId { get; set; }
[Display(Name ="Description")]
[Required(ErrorMessage ="Description is required")]
[StringLength(100,MinimumLength =10)]
public string Description { get; set; }
[Display(Name = "Start Date")]
[Required(ErrorMessage ="Start date is required")]
public DateTime StartDate { get; set; }
[Display(Name = "End Date")]
[Required(ErrorMessage ="End date is required")]
public DateTime EndDate { get; set; }
[Display(Name = "Text To Date Picker")]
public Nullable<DateTime> TestDate { get; set; }
}
查看:
@model DotNet6MVCWebApp.Models.Todo
@{
ViewBag.Title = "Edit";
}
<h2>Edit Item</h2>
@using (Html.BeginForm("Edit", "Todo", FormMethod.Post))
{
<div class="col-sm-3">
<div class="form-group">
@Html.EditorFor(m => m.ItemId,
new { htmlAttributes = new {@class = "form-control",type="hidden"} })
</div>
<div class="form-group">
@Html.LabelFor(m => m.Description)
@Html.EditorFor(m => m.Description,
new { htmlAttributes = new { @class = "form-control"} })
@Html.ValidationMessageFor(m=>m.Description)
</div>
<div class="form-group">
@Html.LabelFor(m => m.StartDate)
@Html.EditorFor(m => m.StartDate,
new { htmlattributes = new { @class = "form-control datepicker",
type="date" } })
@Html.ValidationMessageFor(m=>m.StartDate)
</div>
<div class="form-group">
@Html.LabelFor(m => m.EndDate)
@Html.EditorFor(m => m.EndDate,
new { htmlattributes = new { @class = "form-control datepicker",
type="date"} })
@Html.ValidationMessageFor(m=>m.EndDate)
</div>
<div class="form-group">
@Html.LabelFor(m => m.TestDate)
@Html.TextBoxFor(model => model.TestDate, "{0:d/M/yyyy}",new { id="textTodate", @class = "form-control", type = "text" })
</div>
<input type="submit" value="Update" class="btn btn-primary" />
</div>
}
脚本:
@section scripts {
<script>
$(document).ready(function () {
$("#textTodate").click(function (e) {
$("#textTodate").prop('type','date');
});
});
</script>
}
Note: This is loading with the existing
date
. While user clicking it to modify I am changing it fromtextbox
todate picker
by its clickevent
输出:
希望以上步骤能相应地指导您。