當通過AJAX發佈表單值到我的控制器(/聯繫人/過程),該模型總是以空來了,ModelState.IsValid永遠是假的。不知道模型爲什麼會變爲空。 AJAX文章正在工作,並有水合參數。
感謝
螢火
參數
Contact.Email [email protected]
Contact.FirstName約翰
Contact.LastName李四
Contact.Message您好
X-請求─使用XMLHttpRequest
contact Submit
視圖模型
namespace GuitarCollector.Models.ViewModels
{
public class ContactViewModel
{
public Contact Contact { get; set; }
}
}
示範
namespace GuitarCollector.Models
{
public class Contact
{
//Primary Key
public int Id { get; set; }
[Display(Name = "First name")]
[Required(ErrorMessage = "Please enter your first name")]
public string FirstName { get; set; }
[Display(Name = "Last name")]
[Required(ErrorMessage = "Please enter your last name")]
public string LastName { get; set; }
[Display(Name = "Email address")]
[Required(ErrorMessage = "Please enter your email address")]
public string Email { get; set; }
[Display(Name = "Message")]
[Required(ErrorMessage = "Please enter your message")]
public string Message { get; set; }
public DateTime DateCreated { get; set; }
}
}
表單
<div id="content">
<div id="Status"></div>
@using (Ajax.BeginForm("Process","Contact", new AjaxOptions{ HttpMethod = "POST", UpdateTargetId = "Status"}))
{
@Html.ValidationSummary(true)
<p><span class="required">* All fields are required.</span></p>
<!-- First Name -->
<div>
@Html.LabelFor(model => model.Contact.FirstName) <span class="required">*</span>
</div>
@Html.EditorFor(model => model.Contact.FirstName)
@Html.ValidationMessageFor(model =>model.Contact.FirstName)
<!-- Last Name -->
<div>
@Html.LabelFor(model => model.Contact.LastName) <span class="required">*</span>
</div>
@Html.EditorFor(model => model.Contact.LastName)
@Html.ValidationMessageFor(model =>model.Contact.LastName)
<!-- Email -->
<div>
@Html.LabelFor(model => model.Contact.Email) <span class="required">*</span>
</div>
@Html.EditorFor(model => model.Contact.Email)
@Html.ValidationMessageFor(model =>model.Contact.Email)
<!-- Message -->
<div>
@Html.LabelFor(model => model.Contact.Message) <span class="required">*</span>
</div>
@Html.TextAreaFor(model => model.Contact.Message)
@Html.ValidationMessageFor(model =>model.Contact.Message)
<div>
<input type="submit" name="contact" id="contact" value="Submit" class="btn"/>
</div>
}
</div>
的控制器
[HttpPost]
public ActionResult Process(ContactViewModel model)
{
if (ModelState.IsValid)
{
model.Contact.DateCreated = DateTime.Now;
db.Contacts.Add(model.Contact);
db.SaveChanges();
return Content("Success!");
}
return Content("Failure");
}
這將是DateTime –
嘗試將' name屬性更改爲別的。 – Zabavsky
謝謝。這是解決方案的一部分。我將提交按鈕名稱和ID屬性重命名爲「contactForm」,並且還必須刪除隱藏字段:Contact.Id和Contact.DateCreated。請將您的答案與解釋一起發佈 – Slinky