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
Addのビューはどのように表示されますか?あなたの質問にあなたが入れたビューコードは何ですか? – Fran
@スラバニ:フォームを記入するために最初に使用したのと同じビューを返す必要があります。それが 'Add.cshtml'でない場合は、フォームが置かれているURLとは異なるURLに投稿しなければならないということです。それは良くないね*。それをしないでください。 –