我是asp.net MVC的新手。在下面的代码中,我正在尝试将记录添加到数据库中。它工作正常,但每次加载视图时它都会向数据库添加空记录。
型号:
public class multi
{
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public string Description { get; set; }
public string DisplayName { get; set; }
public string Email { get; set; }
}
public class CategoryRepository
{
private BusDataClassesDataContext dc = new BusDataClassesDataContext();
public void Save()
{
dc.SubmitChanges();
}
public void AddMulti(multi mu)
{
tblCategory cat = new tblCategory();
cat.CategoryName = mu.CategoryName;
cat.Description = mu.Description;
tblUser user = new tblUser();
user.DisplayName = mu.DisplayName;
user.Email = mu.Email;
dc.tblCategories.InsertOnSubmit(cat);
dc.tblUsers.InsertOnSubmit(user);
}
}
控制器:
CategoryRepository cat = new CategoryRepository();
public ActionResult AddMulti(multi mu)
{
if (ModelState.IsValid)
{
cat.AddMulti(mu);
cat.Save();
return View(mu);
}
else
{
return View(mu);
}
}
查看:
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%: Html.LabelFor(model => model.CategoryName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.CategoryName) %>
<%: Html.ValidationMessageFor(model => model.CategoryName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Description) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Description) %>
<%: Html.ValidationMessageFor(model => model.Description) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.DisplayName) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.DisplayName) %>
<%: Html.ValidationMessageFor(model => model.DisplayName) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Email) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Email) %>
<%: Html.ValidationMessageFor(model => model.Email) %>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
答案 0 :(得分:1)
这是因为您没有对模型进行验证,因此ModelState.IsValid
始终为真。然后,您通过AddMulti
添加新类别。因为此控制器方法是唯一指定的方法,所以它用于GET和POST请求。这意味着,每次加载页面并渲染表单时,都会在模型中创建一个包含空值的新记录。
尝试将您的Controller拆分为HttpPost
和HttpGet
方法:
[HttpPost]
public ActionResult AddMulti(multi mu)
{
if (ModelState.IsValid)
{
cat.AddMulti(mu);
cat.Save();
return View(mu);
}
else
{
return View(mu);
}
}
[HttpGet]
public ActionResult AddMulti()
{
return View();
}
现在,当您通过GET请求访问该页面时(即,在发布表单之前首次访问该页面时),将触发第二个操作方法,因此您不会创建该新记录。
您可能还想为模型添加一些验证属性。因为看起来您将域模型直接传递给视图,所以您还应该考虑创建单独的view models。