我有這個複選框,它的工作原理......但每次表單提交複選框都會被取消選中。你不會相信我已經花在論壇上的時間和沮喪,而Google只是看着所有的答案,但我需要這個看似簡單的問題。早上浪費了。如何保留MVC /剃鬚刀中複選框的狀態?
這裏就是該複選框在我看來顯示出來:
@using (Html.BeginForm())
{
<p> Search Criteria: @Html.TextBox("searchString") <br />
<input type="submit" value="Filter" /></p>
<p>Show only my posts: <input type="checkbox" name="authorFilter" onchange="this.form.submit();"/></p>
}
這裏的地方控制器處理這些東西:
public ActionResult Index(string searchString)
{
var posts = from p in db.BlogPosts
select p;
var authorFilterCheck = Request.Form["authorFilter"];
if (authorFilterCheck == "on")
{
string userID = User.Identity.GetUserId();
posts = posts.Where(i => i.AuthorID.Equals(userID));
}
if (!string.IsNullOrEmpty(searchString))
posts = posts.Where(
x =>
x.Body.Contains(searchString) ||
x.Title.Contains(searchString));
return View(posts);
}
所以當它的檢查,它增加了一個過濾器和網頁刷新。但是當刷新時,複選框沒有被選中(但是過濾器仍然被應用),所以你永遠不能刪除過濾器(加上空的複選框會導致用戶認爲沒有過濾器)...
這是模型它的需要:
public class BlogPost
{
[Key]
public int PostID { get; set; }
public string AuthorID { get; set; }
public string Title { get; set; }
public string Body { get; set; }
[Display(Name = "Date Authored")]
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public System.DateTime DateCreated { get; set; }
}
也沒什麼可說在我的模型的複選框,因爲據推測,將其布爾添加到表中的所有條目。對不起,我是新手。
相反,使用Viewbag來保存檢查的數據,這樣你就不必將它包含在模型中,如果你正在爲你的模型使用'IEnumreable',如果bool在模型的實例中,使用'Model [特定模型類的索引] .IsChecked.' –
mahlatse
同時,我設法通過ViewBag方法(這不是我在我的教程中學習的東西)勉強找到一些功能,但我仍然希望我能理解如何執行對的。 – Methodician