我有这个复选框,它的工作原理......但每次表单提交复选框都会被取消选中。你不会相信我已经花在论坛上的时间和沮丧,而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