我是 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>