ASP.NET MVC 2 미리보기 1- 복잡한 모델 객체를 사용한 데이터 안노화 유효성 검사

StackOverflow https://stackoverflow.com/questions/1365511

문제

모델이 자체 유효성 검사를 처리하도록하는 기능으로 인해 MVC 2 미리보기 릴리스를 시작하게되었습니다. 지금까지 나는 검증 체계의 단순성을 좋아합니다. 그러나 나는로드 블록에 빠졌다. 이 검증 스타일은 간단한보기 모델 객체에 적합합니다. 예를 들어 모델 객체가 이름이있는 경우 자동차 그리고 나는 새 차를 만들기 위해보기를 만들고자합니다.

-----모델-------

public class Car
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Color { get; set; }
}

-----제어 장치---------

public class CarController : Controller
{
    public ActionResult Create()
    {
        Car myCar = new Car();
        return View("Create", myCar);

    }

    [HttpPost]
    public ActionResult Create(Car myCar)
    {
        if (!ModelState.IsValid)
        {
            return View("Create", myCar);
        }

        //Do something on success
        return View("Index");

    }

}

-------보다--------------

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Car>" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>

    <% 
        using (Html.BeginForm()) {%>

        <fieldset>
            <legend>Edit User Profile</legend>
            <p>
                <label for="Id">Id:</label>
                <%= Html.TextBox("Id", Model.Id)%>
                <%= Html.ValidationMessage("Id") %>
            </p>
            <p>
                <label for="Name">Name:</label>
                <%= Html.TextBox("Name", Model.Name)%>
                <%= Html.ValidationMessage("Name") %>
            </p>
            <p>
                <label for="Color">Color:</label>
                <%= Html.TextBox("Color", Model.Color)%>
                <%= Html.ValidationMessage("Color") %>
            </p>

            <p>
                <input type="submit" value="Save" />
            </p>
        </fieldset>

    <% } %>

</asp:Content>

이것은 매력처럼 작동합니다. 그러나 내 견해 나 그 문제에 대한 모델 객체가 간단하지는 않습니다. 다음과 같은 자동차 모델 객체가있을 수 있습니다.

-----모델-------

public class PaintScheme
{
    public int Red { get; set; }
    public int Blue { get; set; }
    public int Green { get; set; }
}

public class Car
{
    public string Id { get; set; }
    public string Name { get; set; }
    public PaintScheme Paint{ get; set; }
}

-------보다--------------

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Car>" %>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>

    <% 
        using (Html.BeginForm()) {%>

        <fieldset>
            <legend>Edit User Profile</legend>
            <p>
                <label for="Id">Id:</label>
                <%= Html.TextBox("Id", Model.Id)%>
                <%= Html.ValidationMessage("Id") %>
            </p>
            <p>
                <label for="Name">Name:</label>
                <%= Html.TextBox("Name", Model.Name)%>
                <%= Html.ValidationMessage("Name") %>
            </p>
            <p>
                <label for="Red">Color Red:</label>
                <%= Html.TextBox("Red", Model.Paint.Red)%>
                <%= Html.ValidationMessage("Red") %>
            </p>
            <p>
                <label for="Blue">Color Blue:</label>
                <%= Html.TextBox("Blue", Model.Paint.Blue)%>
                <%= Html.ValidationMessage("Blue") %>
            </p>
            <p>
                <label for="Green">Color Green:</label>
                <%= Html.TextBox("Green", Model.Paint.Green)%>
                <%= Html.ValidationMessage("Green") %>
            </p>

            <p>
                <input type="submit" value="Save" />
            </p>
        </fieldset>

    <% } %>

</asp:Content>

내가 추가 할 때 Paintscheme 내 견해에 따라 속성은 "MyCar"객체가 내 컨트롤러 동작으로 전달 된 상태에서 이월되지 않습니다. 양식 컬렉션에서 객체를 재구성 한 다음 Modelstate를 확인하지 않고도 이것을 해결할 수있는 방법이 있습니까?

도움이 되었습니까?

해결책

  1. 당신은 있어야합니다 공개 세터 속성의 경우 구속되기를 원합니다. 모든 것이 사적이기 때문에 첫 번째 샘플이 어떻게 당신에게 어떻게 작동하는지 궁금합니다.
  2. 당신은해야합니다 하나 이상의 값을 게시하십시오 그것을 묶을 수있는 paintscheme 속성의.
  3. 모든 아동 속성은 다음과 관련이 있어야합니다 그것에. 어디에 *(PropertyName)로 정의 할 수 있습니다. **.

포인트 3은보기에서 만족하지 않는 것 같습니다. 보기의 적절한 부분을 이것으로 변경하십시오.

        <p>
            <label for="Red">Color Red:</label>
            <%= Html.TextBox("Paint.Red")%>
            <%= Html.ValidationMessage("Red") %>
        </p>
        <p>
            <label for="Blue">Color Blue:</label>
            <%= Html.TextBox("Paint.Blue")%>
            <%= Html.ValidationMessage("Blue") %>
        </p>
        <p>
            <label for="Green">Color Green:</label>
            <%= Html.TextBox("Paint.Green")%>
            <%= Html.ValidationMessage("Green") %>
        </p>

또한 NullReferenceException을 피하기 위해 TextBox 도우미에서 명시적인 값을 제거했습니다.

다른 팁

이것을 다루는 가장 쉬운 방법은 DTO를 사용하여 모델을 평평하게하는 것입니다. 그런 다음 Automapper를 사용하여 도메인 객체를 뷰 모델에 매핑하십시오. 이 번역은 열거를 문자열로 변환하는 방식으로 정의 될 수 있습니다. 그러면 유효성 검사가 작동하고 BOM은 우려 사항을 상당히 잘 유지하는 견해에 닿지 않습니다.

색상 부품의 경우 이와 같은 것을 가질 수 있습니다. int 일 때 텍스트 상자를 사용한다고 생각하지 않지만 붉은 색상을 바인딩합니다 (입력 값이 숫자 인 경우).

 <p>
                <label for="Red">Color:</label>
                <%= Html.TextBox("Red", Model.Paint.Red)%>
                <%= Html.ValidationMessage("Red") %>
 </p>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top