2014-11-05 1 views
2

양식이 다시 게시되고 모델이 손실되는 문제가 있습니다. 페이지가 다시 게시되자 마자 객체가 이미 존재하더라도 .net은 객체의 기본 생성자를 호출합니다.POST 도중 기본 생성자가 호출되고 모든 모델 데이터가 손실됩니다.

나는이 개 행동, POST

 [HttpGet] 
     public ActionResult Quote(string sku, string network, string grade) 
     { 
      QuoteModel qm = new QuoteModel(); 
      // build model here 
      return View("Quote", qm); 
     } 
     [HttpPost] 
     public ActionResult Quote(QuoteModel qm, string grade, string network) 
     { 
      // update model 
      return View("Quote",qm); 
     } 

에 대한 GET 하나 하나 가져 오기 기능은 완벽하지만 곧 양식이 게시 될 때, 기본 생성자가 호출 작품을하고 난 모든 모델 데이터를 잃게됩니다.

내보기 같다 :

@model PriceCompare.Models.QuoteModel 

    <div class="clarify"> 
     @if (Model.clarify == true) 
     { 


      using (Html.BeginForm("Quote", "Home", FormMethod.Post)) 
      { 

      @Html.DropDownList("network", Model.availableNetworks); 
      @Html.DropDownList("grade", Model.grades); 

      <button type="submit">Get Quote</button> 
      } 

     } 
    </div> 

돌려 보내는 기존 모델이있을 때 왜 기본 생성자가 호출되고?

내가 좋아하는 형태로 모델을 지정 시도

: 나는 기본 생성자가 호출되지 않는 한 후이 작업을 수행 할 경우

using (Html.BeginForm("Quote", "Home", new { @qm = Model}, FormMethod.Post) 

하지만 qm은 null입니다.

저는 이것을 알아 내려고 여기 서클을 돌았습니다. 아무도 내가 뭘 잘못하고 있다고 설명 할 수 있습니까?

+0

다르게 POST 작업을 명명하지 왜? 문제를 해결해야합니다 ... – Charlie

+0

@Charlie 방금 POST 메서드를 "QuoteUpdate()"로 변경해 보았습니다. 기본 생성자는 여전히 같은 방식으로 호출됩니다. – Guerrilla

+0

바꾸기 : @using (Html.BeginForm (actionName : "QuoteUpdate", ControllerName : "Home")) – Charlie

답변

0

생성자를 오버로드하고 부울 매개 변수를 true로 설정하여 두 번째 생성자를 명시 적으로 호출하면이 문제를 해결할 수 있습니다.

모델

public class MyModel 
{ 
    public int NumberRequested { get; set; } 

    // This constructor will be called by MVC 
    public MyModel() 
    { 
     RefreshReport(); 
    } 

    // Call this constructor explicitly from the controller 
    public MyModel(bool load) 
    { 
     if (!load) 
     { 
      return; 
     } 

     NumberRequested = 10; 

     RefreshReport(); 
    } 

    public void RefreshReport() 
    { 
     // Do something 
    } 
} 

생성자

public class MyController 
{ 
    public ActionResult MyView() 
    { 
     var myModel = new MyModel(true); 

     return View(myModel); 
    } 

    [HttpPost] 
    public ActionResult MyView(MyModel myModel) 
    { 
     myModel.RefreshReport(); 

     return View(myModel); 
    } 
} 
관련 문제