ฉันกำลังพยายามแสดงแบบฟอร์มเพื่อให้ผู้ใช้กรอก จากนั้นฉันจะบันทึกบันทึกนั้น หากข้อมูลไม่ถูกต้อง ฉันต้องการแจ้งให้ผู้ใช้ทราบถึงปัญหาการตรวจสอบแบบคลาสสิก
ฉันกำลังลองใช้โค้ดนี้ แต่เมื่อโมเดลไม่ถูกต้อง มันจะแสดงข้อผิดพลาด แต่จริงๆ แล้วโมเดลจะส่งคืนเฉพาะสิ่งที่อยู่ในมุมมองบางส่วนเท่านั้น มันไม่ได้โหลดเลย์เอาต์หรือฟอร์มโมดอลของฉัน ทั้งหมดที่ฉันได้รับคือหน้าสีขาวที่มีเพียงบางส่วนของฉัน
แล้วฉันทำอะไรผิด?
นี่คือรูปแบบกิริยาช่วยของฉัน:
และหลังจากการตรวจสอบความถูกต้องแล้ว สิ่งที่ฉันได้รับคือ:
รหัส: รุ่น:
public class Car
{
public int Id { get; set; }
[Required]
[StringLength(50, MinimumLength = 6)]
public string Model { get; set; }
public string Brand { get; set; }
public string Year { get; set; }
public string Color { get; set; }
}
ดู:
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add Car</h4>
</div>
<div class="modal-body">
@Html.Partial("CreatePartialView",new Car())
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="savechanges">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
บางส่วนของฉัน:
@model ControliBootstrap.Models.Car
@using (Ajax.BeginForm("ModalAdd", "Cars",new AjaxOptions()
{
UpdateTargetId = "mymodalform"
}))
{
<div class="form-horizontal" id="mymodalform">
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.Model, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Model)
@Html.ValidationMessageFor(model => model.Model)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Brand, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Brand)
@Html.ValidationMessageFor(model => model.Brand)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Year, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Year)
@Html.ValidationMessageFor(model => model.Year)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Color, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Color)
@Html.ValidationMessageFor(model => model.Color)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
และในที่สุดผู้ควบคุมของฉัน:
public ActionResult ModalAdd(Car car)
{
if (ModelState.IsValid)
{
db.Cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
return PartialView("CreatePartialView",car);
}