2

에서 null을 반환 내 HTTP 게시물입니다 : 내 GET에서 그것을 채우기왜이 내 모델 내보기 모델

public class Attribute 
{ 
    public string Key { get; set; } 
    public string Value{ get; set; } 
} 

만들

public ActionResult Create() 
    { 
     var Attributes = new[] 
     { 
      new Attribute {Key = "Name" Value = "" }, 
      new Attribute {Key = "Age" Value = "" }, 
     }; 
     return View(Attributes); 
    } 

내보기 다음과 같습니다

@model IEnumerable<Customers.ViewModels.Attribute> 
@using (Html.BeginForm()) 
{ 
    @Html.ValidationSummary(true) 

    <fieldset> 
     @foreach (var item in Model) 
     { 
      <div class="editor-label"> 
       @Html.Label(item.Key) 
      </div> 
      <div class="editor-field"> 
       @Html.EditorFor(m => item.Value) 
       @Html.ValidationMessageFor(m => item.Value) 
      </div> 
     } 
     <p> 
      <input type="submit" value="Create" /> 
     </p> 
    </fieldset> 
} 

내 게시물 작성은 다음과 같습니다.

[HttpPost] 
    public ActionResult Create(IEnumerable<Attribute> attributes) 
    { 
    } 

그러나 내 IEnumerable<Attribute> attributes은 null입니다. 어떤 제안?

+0

귀하의 GET이 반환됩니다. 속성이 아닙니다. –

+0

예, 그렇습니다. – Pittfall

+0

입니다. IEnumerable <>을 (를) 예상하고 있습니다. 내 잘못입니다. –

답변

3

Attribute에 대한 편집기 템플릿을 만든 다음 List<Attribute> 모델을 전달해야합니다. 보기 사용에

@Model Attribute 
<div class="editor-label"> 
    @Html.LabelFor(m => m.Key) 
</div> 

<div class="editor-field"> 
    @Html.EditorFor(m => m.Value) 
    @Html.ValidationMessageFor(m => item.Value) 
</div> 

는 다음 foreach이 요소에 대한 올바른 이름을 생성하지 않기 때문에

<fieldset> 
    @Html.EditorFor(m > m) 

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

이 작업을 수행해야합니다.

+0

이 작품은 작동하지만 왜 그렇게해야만하는지 설명 할 수 있습니까? 조금만 더? 나는 아직도 그것을 이해하지 못했다. – Pittfall

+0

또한보기에 사용하지 않는 모델의 값이있는 경우 로직에 사용하는 경우 어떻게 게시물의 값을 유지할 수 있습니까? – Pittfall

+0

객체 목록을 전달하면 html 요소의 이름은 'Attribute [0] .Property'형식이어야합니다. html을 확인하면 foreach가 렌더링하지 않는다는 것을 알 수 있습니다. – MuriloKunze