MVC3에서 Entity Framework를 사용하고 있습니다. 사용자가 새 레코드를 추가 할 때 유효성을 검사 할 두 가지 속성이있는 Product라는 엔터티가 있습니다. 이를 위해, 나는 그래서, 버디 클래스를 만들었습니다MVC3의 드롭 다운 목록 유효성 검사?
using System;
using System.ComponentModel.DataAnnotations;
namespace Rpm.Data.Partials
{
[MetadataType(typeof(ProductMetadata))]
public partial class Product
{
}
}
메타 데이터 클래스는 이렇게이다 :
using System;
using System.ComponentModel.DataAnnotations;
namespace Rpm.Data.Partials
{
public class ProductMetadata
{
[Required]
public string ProductName { get; set; }
[Range(200, 1000, ErrorMessage = "You must select a valid Account Type")]
public int AccountTypeId { get; set; }
}
}
사용자가 새 레코드를 추가 할 수 있습니다 뷰는 다음과 같이이다 :
@model Rpm.Data.Product
@{
ViewBag.Title = "Product"
}
<script type="text/javascript">
$(document).ready(function() {
//There should be no selection in the drop-down box when the form is first displayed.
document.getElementsByTagName("select")[0].selectedIndex = -1;
}
function formSubmit() {
var form = $("form");
if (form.valid()) {
(event.preventDefault) ? event.preventDefault() : event.returnValue = false;
document.getElementById("frmNewProduct").submit();
return true;
}
else {
return false;
}
}
</script>
<h2>Add New Product</h2>
@using (Html.BeginForm("Create", "Product", new { id = new Product() }, FormMethod.Post, new { id = "frmNewProduct" }))
{
@Html.ValidationSummary(true)
<table>
<tr>
<td>
Product Name
</td>
<td>
@Html.TextBoxFor(m => new Product().ProductName)
@Html.ValidationMessageFor(m => new Product().AccountTypeId)
</td>
</tr>
<tr>
<td>
Account Type
</td>
<td>
@Html.DropDownListFor(m => new Product().AccountTypeId, new SelectList(Lookup.Instance.AccountTypes, "AccountTypeId", "AccountTypeName"))
@Html.ValidationMessageFor(m => new Product().AccountTypeId)
</td>
</tr>
<tr>
<td />
<td>
<input type="image" src="@Url.Content("~/Content/images/savebutton.png")" onclick="return formSubmit()" />
</td>
</tr>
</table>
}
(물론, 위 아주 정말 관련이 아니에요 코드로 포스트 과부하를 방지하기 위해 단지 단순화된다.)
문제는 사용자가 저장 버튼을 클릭하면 ProductName에 대한 유효성 검증이 정상적으로 작동하고 필드가 비어 있으면 유효성 검사 메시지가 표시된다는 것입니다. 그러나 드롭 다운이 선택없이 (selectedIndex == -1)
없이 남아 있더라도 AccountTypeId에 대한 메시지는 표시되지 않습니다. 엔티티에 대한 변경 사항을 저장할 때 EF가 DbEntityValidationException
을 던지고 ErrorMessage의 텍스트가 메타 데이터에 지정된 사용자 정의 오류 메시지이기 때문에 AccountTypeId의 RangeAttribute
이 선택되었음을 압니다. 난 그냥 페이지에 표시하고 양식 유효성 검사를 실패하게, 사용자가 저장하지 못하게 할 수 없습니다.
제가 잘못하고있는 것에 대한 어떤 제안이라도 가장 감사하겠습니다!
TIA,
팁 주셔서 감사합니다 - 내가 알 수 있듯이, 나는이 부분에서 매우 초록색이므로 얻을 수있는 모든 조언이 필요합니다! :-) 당신의 첫 번째 요점에, 나는 알고있다. 문제는이보기에도 기존 제품이 포함되어 있다는 것입니다 (앞에서 언급했듯이 게시를 위해 단순화했습니다 - 어쩌면 너무 많음). 아마도 제품 제작 물건을 부분보기에 넣어야합니까? 'AccountTypeId'와 관련하여, 기본 db 컬럼은 널 입력이 불가능합니다. 이 경우 해당 속성을 nullable로 만들 수 있습니까? – JTennessen
부분보기 접근 방식은 매력처럼 작동했습니다. 그 방향으로 나를 가리켜 주신 것에 대해 감사드립니다! 나는 심지어 AccountTypeId를 null로 만들지 않아도되지 못했습니다. :-) – JTennessen