2 回答

TA貢獻1862條經(jīng)驗 獲得超6個贊
對于單選按鈕,我將向您的 BuildSearch 類添加一個名為 GeoAreaId 的屬性。單選按鈕選擇將在回發(fā)時模型綁定到此屬性。因此,您的 BuildSearch 類變?yōu)?/p>
public class BuildSearch
{
//Bootstrap date entry
public DateTime StartDate { get; set; }
//Bootstrap date entry
public DateTime EndDate { get; set; }
public int GeoAreaId { get; set; } //added field
//Need this bound to a radio button list
public List<GeoArea> GeoAreas { get; set; }
public BuildSearch()
{
GeoAreas = new List<GeoArea>();
// StartDate = DateTime.Parse(DateTime.Now.AddDays(-31).ToShortDateString());
// EndDate = DateTime.Parse(DateTime.Now.ToShortDateString());
GeoAreas.Add(new GeoArea { GeoAreaItem = "Region", Id = 0 });
GeoAreas.Add(new GeoArea { GeoAreaItem = "Manager1", Id = 1 });
GeoAreas.Add(new GeoArea { GeoAreaItem = "Manager2", Id = 2 });
}
public class GeoArea
{
public int Id { get; set; }
public string GeoAreaItem { get; set; }
}
}
你的控制器中的 get 方法看起來像這樣
public IActionResult Search()
{
var buildSearch = new BuildSearch();
return View(buildSearch);
}
你的視圖需要看起來像這樣
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@model BuildSearch
<form asp-controller="Home" asp-action="Search" method="post">
<label asp-for="StartDate">Start date</label>
<input asp-for="StartDate" />
<label asp-for="EndDate">End date</label>
<input asp-for="EndDate" />
<fieldset>
<legend>
GeoArea
</legend>
@foreach (var item in Model.GeoAreas)
{
<input type="radio" name="GeoAreaId" value="@item.Id" />
@item.GeoAreaItem
}
</fieldset>
<input type="submit" />
</form>
對于單選按鈕,請注意 name 屬性如何與我添加到 BuildSearch 類中的新屬性 GeoAreaId 相匹配。這對于模型綁定的工作非常重要。
然后你的控制器中的 post 方法將需要如下所示
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Search(BuildSearch buildSearch)
{
//...
}
要查看發(fā)生了什么,請在此方法中設置一個斷點。運行代碼,在表單中輸入一些值,然后單擊提交。當代碼停止在 buildSearch 上時,您將看到模型綁定已起作用。屬性 StartDate、EndDate 和 GeoAreaId 將包含表單中所需的值。

TA貢獻1798條經(jīng)驗 獲得超7個贊
將數(shù)據(jù)放入視圖模型中,您將執(zhí)行類似的操作
public async Task<IActionResult> Index()
{? ??
? ? var movies = await _context.Movies.ToList();
? ? if (movies == null)
? ? {
? ? ? ? return NotFound();
? ? }
? ? return View(movies);
}
然后,您將需要該表格來對您的操作進行后續(xù)操作,例如
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,Title,ReleaseDate,Genre,Price")] Movie movie)
{? ??
? ? if (ModelState.IsValid)
? ? {
? ? ? ? ? ? //post to api here
? ? ? ? return RedirectToAction(nameof(Index));
? ? }
? ? return View(movie);
}
您必須將模型或視圖模型傳遞到 html 類中,如下所示
@model MvcMovie.Models.Movie
@{
? ? ViewData["Title"] = "Edit";
}
<h1>Edit</h1>
<h4>Movie</h4> etc etc
- 2 回答
- 0 關注
- 152 瀏覽
添加回答
舉報