2014-10-31 3 views
0

데이터베이스에서 벗어난 편차 항목 목록이 있습니다. 목록에 심각도가이며 null 일 수 있습니다. 그 이유는 내가 SeverityNotNull 속성을 null 값을 -1로 변환했기 때문입니다. BTW 심각도는 0-3이 될 수 있습니다.DropDownList에서 선택한 항목 설정

표시하려고합니다. 편도 각 심각도는 줄 단위로 DropdownList 여야하는 항목입니다. 물론 DropdownList에서 적절한 항목을 선택해야합니다.

내 뷰 모델은 다음과 같습니다

[MetadataType(typeof(DeviationMetaData))] 
public partial class Deviation { 
    public int SeverityNotNull { 
     get { return Severity == null ? -1 : Severity.Value; } 
    } 
    ... 
} 

public class DeviationMetaData { 
    public Nullable<int> Severity { get; set; } 
    ... 
} 

public class DeviationViewModel { 

    public Deviation Dev { set; get; } 
    public IEnumerable<Deviation> Deviations { 
     get { 
      DeviationRepository dm = new DeviationRepository(); 
      return dm.GetAll; 
     } 
    } 

    public DeviationViewModel() { 
     WindowsIdentity current = WindowsIdentity.GetCurrent(); 
     string name = current.Name.Split(new[] { '\\' })[1]; 

     Dev = new Deviation { CreatedBy = name, CreatedDate = DateTime.Now }; 
    } 
} 

내 컨트롤러는 다음과 같습니다

@model DeviationViewModel 
    @using (Html.BeginForm()) { 
      <table> 
       <tr> 
        <th> 
         @Html.DisplayNameFor(model => model.Dev.Severity) 
        </th> 
       </tr> 
       @foreach (var item in Model.Deviations) { 
        <tr> 
         <td> 
          @Html.DropDownListFor(modelItem => item.SeverityNotNull, (SelectList)ViewBag.SelectSeverity) 
         </td> 
        </tr> 
       } 
      </table> 
     </fieldset> 
    } 
</div> 

내가 SeverityNotNull 값을 확인하고 그들은 올바른 :

public ActionResult Index() { 
    IList<SelectListItem> items = new List<SelectListItem> { 
     new SelectListItem{Text = "", Value = "-1"}, 
     new SelectListItem{Text = "Minor", Value = "1"}, 
     new SelectListItem{Text = "Major", Value = "2"}, 
     new SelectListItem{Text = "Critical", Value = "3"} 
    }; 
    ViewBag.SelectSeverity = new SelectList(items, "Value", "Text"); 

    return View(new DeviationViewModel()); 
} 

내보기입니다. 결과에는 드롭 다운리스트가 있지만 아무것도 선택되지 않습니다. 이것이 문제입니다. 몇 가지 아이디어를 제공해 주시겠습니까? 감사.

+0

'Severity'가 null 일 수있는 경우,'SeverityNotNull'의 요점은 무엇입니까? 왜 널 값을 -1로 변환해야합니까? 이 모든 잘못에 대한 당신의가는 그리고 심지어는 어쨌든 –

+0

-1은 Dropdownlist에서 빈 텍스트의 색인을하려고합니다 다시 게시에 바인딩되지 않습니다. 분명히 null은 인덱스가 될 수 없습니다. 왜 틀렸어? 어쨌든 당신의 아이디어는 무엇입니까? – Franziee

+0

그렇게하지 않아도됩니다. 다른 여러 문제가 있으므로 곧 답변을 게시하겠습니다. 뷰 모델에는 데이터베이스 액세스 코드가 없어야합니다. –

답변

1

SeverityNotNull 속성을 만들 필요는 없습니다. SelectList에는 null 값이있는 옵션이 포함될 수 있습니다.이 옵션을 선택하면 null을 되돌릴 수 있습니다. 루프 (중복 게시하지 않음) 및 id 속성 (잘못된 html)을 중복하여 <selects>을 렌더링하는 foreach 루프를 포함하여 여러 가지 다른 문제가 있습니다. 뷰 모델을 만들어

시작은 Deviation

public class DeviationVM 
{ 
    public int ID { get; set; } 
    public int? Severity { get; set; } 
    // other properties of the Deviation data model that you want to edit/display 
} 

컨트롤러

public ActionResult Index() 
{ 
    // Get your deviations and map to the view model 
    List<DeviationVM> model = dm.GetAll().Select(d => new DeviationVM 
    { 
    ID = d.ID, 
    Severity = d.Severity 
    }).ToList(); 
    // create your select list (
    var severityList = new[] { new { ID = 1, Name = "Minor" }, new { ID = 2, Name = "Major" }, new { ID = 2, Name = "Critical" } }; 
    ViewBag.SeverityList = new SelectList(severityList, "ID", "Name"); 
    return View(model) 
} 

public ActionResult(List<DeviationVM> model) 
{ 
    ... 
} 

보기

@model List<DeviationVM> 

@using (Html.BeginForm()) { 
    .... 
    for(int i = 0; i < Model.Count; i++) 
    { 
    @Html.HiddenFor(m => m[i].ID) 
    @Html.DropDownListFor(m => m[i].Severity, (SelectList)ViewBag.SeverityList, "Text for null value") 
    } 

참고 올바르게있는 <select name="[0].Severity" ..> <select name="[1].Severity" ..>를 생성 for 루프의 사용을 나타내는 인덱서 이름 게시물에 다시 바인딩됩니다. @Html.DropDownListFor()의 오버로드를 사용하면 <option value>Text for null value</option> <option value="1">Minor</option> ...이라는 옵션이 생성됩니다. 첫 번째 옵션에는 값이 없으므로이 값을 선택하면 다시 게시 할 때 Severity 속성 값이 null이됩니다.

속성 Severity의 값이 initiallt 인 경우 첫 번째 옵션이 기본적으로 선택됩니다. 값이 2이면 기본적으로 세 번째 옵션이 선택됩니다.

관련 문제