私はasp.net MVCが初めてです。以下のコードでは、データベースにレコードを追加しようとしています。正常に動作しますが、ビューをロードするたびに null レコードがデータベースに追加されます。
モデル:
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>