0
public ActionResult Add(Models.ContactModel contact)
{
if (ModelState.IsValid)
{
DAL.Contact mappedContact = Mapper.Map<Models.ContactModel, DAL.Contact>(contact);
repository.AddContact(mappedContact);
return RedirectToAction("Index");
}
else
/* What to return here */
}
这是用于将联系人添加到数据库的控制器。我正在使用数据注释验证表单,如果表单有效,我将它重定向到索引页面。如果它无效,它应该保持在显示错误信息的同一页面上。在其他部分写什么。任何人都可以建议我。对于添加控制器没有看法。如果表格无效,请保持在同一页面
<div>
<label>Name</label>
@Html.ValidationMessageFor(model => model.Name, null, new { @class = "error-message"})
@Html.TextBoxFor(model => model.Name, new { @class = "long-box" })
</div>
<div>
<label>Email</label>
@Html.ValidationMessageFor(model => model.Email, null, new { @class = "error-message" })
@Html.TextBoxFor(model => model.Email, new { @class = "long-box" })
</div>
<div class="mob-land-container">
<label>Mobile</label>
@Html.ValidationMessageFor(model => model.MobileNumber, null, new { @class = "error-message" }) <br>
@Html.TextBoxFor(model => model.MobileNumber, new { @class = "short-box" })
</div>
<div class="mob-land-container" id="landline-container">
<label>Landline</label>
@Html.ValidationMessageFor(model => model.LandlineNumber, null, new { @class = "error-message" })<br>
@Html.TextBoxFor(model => model.LandlineNumber, new { @class = "short-box" })
</div>
<div>
<label>Website</label>
@Html.ValidationMessageFor(model => model.Website, null, new { @class = "error-message" })
@Html.TextBoxFor(model => model.Website, new { @class = "long-box" })
</div>
<div>
<label>Address</label>
@Html.ValidationMessageFor(model => model.Address, null, new { @class = "error-message" })
@Html.TextAreaFor(model => model.Address, new { @class = "address-box" })
</div>
</div>
<div class="button-container">
<input type="button" id="cancel" value="Cancel" onclick="location.href='@Url.Action("Index", "Contact")'" />
<input type="submit" id="add" value="Add" onclick="location.href='@Url.Action("Add", "Contact")'" />
</div>
这是我得到数据到控制器的形式。
public class ContactModel
{
public int Id { get; set; }
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
[Required(ErrorMessage = "Email is required")]
public string Email { get; set; }
[Required(ErrorMessage = "Mobile Number is required")]
public string MobileNumber { get; set; }
[Required(ErrorMessage = "Landline Number is required")]
public string LandlineNumber { get; set; }
[Required(ErrorMessage = "Website is required")]
public string Website { get; set; }
[Required(ErrorMessage = "Address is required")]
public string Address { get; set; }
}
这是模型类。
在此先感谢。
没有视图添加控制器...它显示错误.... – Sravani
如何没有添加视图?你在问题中提出的观点代码是什么? – Fran
@Sravani:您需要返回用户最初用来填写表单的相同视图。如果这不是'Add.cshtml',那么这意味着您必须发布到与表单所在网站不同的网址。那很糟*。不要这样做。 –