我是新來的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>
你是否缺少模型中的[[Required]]? – 2013-04-23 07:40:06