Bên trong hành động điều khiển của tôi Tôi có đoạn mã sau:Cách thêm lỗi xác thực trong bộ sưu tập xác thực asp.net mvc?
public ActionResult GridAction(string id)
{
if (String.IsNullOrEmpty(id))
{
// add errors to the errors collection and then return the view saying that you cannot select the dropdownlist value with the "Please Select" option
}
return View();
}
UPDATE:
if (String.IsNullOrEmpty(id))
{
// add error
ModelState.AddModelError("GridActionDropDownList", "Please select an option");
return RedirectToAction("Orders");
}
UPDATE 2:
Đây là mã cập nhật của tôi:
@Html.DropDownListFor(x => x.SelectedGridAction, Model.GridActions,"Please Select")
@Html.ValidationMessageFor(x => x.SelectedGridAction)
The Model loo ks như sau:
public class MyInvoicesViewModel
{
private List<SelectListItem> _gridActions;
public int CurrentGridAction { get; set; }
[Required(ErrorMessage = "Please select an option")]
public string SelectedGridAction { get; set; }
public List<SelectListItem> GridActions
{
get
{
_gridActions = new List<SelectListItem>();
_gridActions.Add(new SelectListItem() { Text = "Export to Excel", Value = "1" });
return _gridActions;
}
}
}
Và đây là hành động điều khiển của tôi:
public ActionResult GridAction(string id)
{
if (String.IsNullOrEmpty(id))
{
// add error
ModelState.AddModelError("SelectedGridAction", "Please select an option");
return RedirectToAction("Orders");
}
return View();
}
Không có gì xảy ra! Tôi hoàn toàn bị mất trên cái này!
UPDATE 3:
bây giờ tôi đang sử dụng đoạn mã sau nhưng vẫn xác nhận là không bắn:
public ActionResult GridAction(string id)
{
var myViewModel= new MyViewModel();
myViewModel.SelectedGridAction = id; // id is passed as null
if (!ModelState.IsValid)
{
return View("Orders");
}
CẬP NHẬT 4:
$("#linkGridAction").click(function() {
alert('link grid action clicked');
$.get('GridAction/', { SelectedGridAction: $("#SelectedGridAction").val() }, function (result) {
alert('success');
});
});
Và Controller trông giống như sau :
// OrderViewModel has a property called SelectedGridAction.
public ActionResult GridAction(OrderViewModel orderViewModel)
{
return View();
}
CẬP NHẬT 5: Xác nhận không bắn:
public ActionResult GridAction(OrderViewModel orderViewModel)
{
if (!ModelState.IsValid)
{
return View("Orders", orderViewModel);
}
return View();
}
Thật không may, có một giá trị khi người dùng chọn tùy chọn "Vui lòng chọn". – johndoe
@johndoe, không nên có. Nếu bạn sử dụng phương thức trợ giúp sau: '<% = Html.DropDownListFor (x => x.Id, Model.Items," - vui lòng chọn - ")%>' để tạo danh sách thả xuống của bạn, sẽ không có giá trị nào được gửi và xác thực sẽ tự động hoạt động. Ngoài ra nó có ý nghĩa hơn để gửi chuỗi rỗng khi người dùng đã không chọn bất cứ điều gì thay vì một số giá trị giả. –
Tôi cũng nên thêm rằng trang không được gửi (không có nút gửi) nhưng một hành động được gọi thông qua một liên kết và đó là lý do tại sao việc xác thực không được kích hoạt! – johndoe