2013-09-30 25 views
0

我想在mvc4剃鬚刀視圖中的httpget上返回空模型。一旦用戶將從下拉列表中選擇值,我將在httppost上獲取模型。 這是我有:mvc4剃鬚刀在httpget上返回空模型

[HttpGet] 
     public ActionResult AddNewAgent() 
     {     
      var modelAgentt = _fe.Agents.Take(1);   
      SelectList sl = new SelectList((from s in _aa.Agent.ToList() select new {COUNTER = s.COUNTER, FullName = s.LASTNAME + ", " + s.FIRSTNAME}), "COUNTER", "FullName", null); 
      ViewBag.Agent= sl; 
      return View(agg); 
     } 

然後在HttpPost我:

[HttpPost] 
     public ActionResult AddNewAgent(int? LamcomAgents) 
     {  
      var modelAgent = _fe.Agents.Take(10); 
      SelectList sl = new SelectList((from s in _aa.Agent.ToList() select new { COUNTER = s.COUNTER, FullName = s.LASTNAME + ", " + s.FIRSTNAME }), "COUNTER", "FullName", null); 
      ViewBag.Agent= sl; 
      if (LamcomAgents != null && LamcomAgents != 0) 
      { 
       return View(modelAgent);     
      } 
      return View(modelAgent);    
     } 

正確的LINQ查詢是不是還包括在httppost行動,但我會做到這一點後,我只是想了解如何在第一次運行時爲httpget傳遞可空模型,而不會在視圖中發生錯誤。 這是我的觀點:

@model IEnumerable<Company.Agents> 

@{ 
    ViewBag.Title = "AddNewAgent"; 
} 

<h2>Add New Agent</h2> 

@using (Html.BeginForm()) { 
    @Html.AntiForgeryToken() 
    @Html.ValidationSummary(true) 

    <fieldset> 
     <p>Agents in System @Html.DropDownList("Agent", String.Empty)&nbsp;&nbsp; <input type="submit" name="Get Agent" value="Get Agent" title="Get Agent" id="btnGetAgent" /></p> 
     <legend>Agents</legend>  
    <table>  
        <tr> 
         <th>@Html.DisplayNameFor(model => model.A_FirstName)</th> 
         <th></th> 
        </tr> 
        <tr> 

        </tr>    
      @foreach(var item in Model) 
      { 
       <tr><td> 
       @Html.DisplayFor(modelItem => item.A_FirstName) 
        </td></tr> 
      } 
       </table> 

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

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 

@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
} 

由於提前,Laziale

+0

什麼是'agg'和定義它?向我們展示它的代碼 – Satpal

回答

1

假設modelAgentt的類型是IEnumerable<Company.Agents>

我認爲你需要通過modelAgentt查看,而不是agg

所以請從中更改您的代碼獲取方法

return View(agg); 

return View(modelAgentt);