【发布时间】:2019-07-14 04:16:55
【问题描述】:
正如描述所说,当我将数据从我的方法的 get 传递到视图时,一切都很好,但是,当我点击保存按钮并转到服务器以验证模型是否有效时,如果它确实有效一切都很好,但是,如果模型无效,他会返回相同的视图(就像应该做的那样),但是当它进入服务器时它丢失了集合,我认为再次填充它太愚蠢了,所以,有什么方法可以只为选择列表填充一次模型?
我有那些动作
public IActionResult Create()
{
var types = _context.Types;
var vm = new EventViewModel
{
Types = new SelectList(types, "Id", "Name")
};
return View(vm);
}
[Authorize]
[HttpPost]
public IActionResult Create(EventViewModel vm)
{
//when it enter here **Types** comes empty
//if is not valid
if (!ModelState.IsValid)
{
//var types = _context.Types;
//**I WANT TO AVOID THIS**
//vm.Types = new SelectList(types, "Id", "Name", vm.TypeId);
return View(vm);
}
var ev = new Event
{
DateTime = vm.GetDateTime(),
TypeId = vm.TypeId,
Venue = vm.Venue,
CoachId = User.FindFirstValue(ClaimTypes.NameIdentifier)
};
_context.Add(ev);
_context.SaveChanges();
return RedirectToAction("Index", "Home");
}
这是我的看法
@model EcCoach.Web.ViewModels.EventViewModel
@{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<form asp-action="Create">
<p class="alert alert-info">
All fields are <strong>required</strong>
</p>
<div class="form-group">
<label asp-for="Venue"> </label>
<input asp-for="Venue" class="form-control" placeholder="Enter a
venue" autofocus="autofocus">
<span asp-validation-for="Venue"></span>
</div>
<div class="form-group">
<label asp-for="Date"> </label>
<input asp-for="Date" class="form-control" placeholder="eg
15/12/2017">
</div>
<div class="form-group">
<label asp-for="Time"> </label>
<input asp-for="Time" class="form-control">
</div>
<div class="form-group">
<label asp-for="TypeId"> </label>
<select asp-for="TypeId" asp-items="@Model.Types" class="form-
control">
<option value="0">Choose One</option>
</select>
</div>
<button type="submit" class="btn btn-primary">
Save
</button>
</form>
最后这是我的 ViewModel
public class EventViewModel
{
[Required]
[FutureDate]
public string Date { get; set; }
[Required]
[ValidTime]
public string Time { get; set; }
[Required]
public byte TypeId { get; set; }
[Required]
[StringLength(5)]
public string Venue { get; set; }
public DateTime GetDateTime()
{
return DateTime.Parse($"{Date} {Time}");
}
public IEnumerable<SelectListItem> Types { get; set; }
}
【问题讨论】:
标签: c# asp.net-core html-helper