2012-06-04 7 views
0

모델을 뷰에 보냈다 고 가정하면 ... 이 모델을 편집하면 저장하려고합니다. 필드 (예 : 개체의 ID)를 모두 쓰지 않으면 어떻게 든 0으로 재설정되거나 비어 있습니다 (문자열 인 경우). 내가 한 일은 숨겨진 필드를 써서이 개체를 저장하려고 할 때 어떤 개체인지 식별 ​​할 수 있습니다 ...강력한 형식의 뷰에서 모델 저장

이 좋은 형태입니까? 아니면 단계가 빠졌습니까?

답변

1

파일 헤더의보기에 모델 유형을 지정했고 Html.BeginForm 도우미 메서드를 사용하는 경우 이미이 ID를 보내는 것이 중요 할 것입니다.

편집 : 테스트 해봤는데, 맞습니다. Html.BeginForm 메서드로 출력을 만들었습니다.

<form action="/Product/Edit/1" method="post"> 

그래서 id를 보내는 이유입니다.

using System.Web.Mvc; 
using MvcApplication2.Models; 

namespace MvcApplication2.Controllers 
{ 
    public class ProductController : Controller 
    { 
     public ActionResult Edit(int id) 
     {    
      return View(new Product { Id = 1, Name = "Test"}); 
     } 

     [HttpPost] 
     public ActionResult Edit(Product product) 
     { 
      return Edit(product.Id); 
     } 

    } 
} 

하고보기 :

@model MvcApplication2.Models.Product 

@using (Html.BeginForm()) { 
    <fieldset> 
     <legend>Product</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.Name) 
     </div> 
     <div class="editor-field"> 
      @Html.EditorFor(model => model.Name) 
      @Html.ValidationMessageFor(model => model.Name) 
     </div> 

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

내가 Html.BeginForm를 사용 할

다음은 내가 그것을 테스트하는 데 사용되는 컨트롤러입니다. 하지만 항상 ID를 0으로 재설정합니다. – SoftwareSavant

+0

컨트롤러에서 보낸 모델을 사용합니다. 경로는 Html.BeginForm이 생성하는 URL에 따라 설정해야합니다. – Adauto

0

괜찮습니다. 객체 ID를 편집하지 않는다면 ID를 숨겨진 입력으로 사용할 수 있습니다.

모든 필드를 게으 르기 작성하는 경우 automapper를 확인하는 것이 좋습니다.