2014-10-16 31 views
1

我有這回事真的很愚蠢的問題。爲什麼我的ASP.NET MVC模型在控制器中填充,但在視圖中爲空?

我有絕對拒絕顯示我的視圖模型的ASP.NET MVC頁。即使我刪除分配給視圖模型數據庫的結果,只是硬編碼我想在控制器內的視圖模型屬性的值,它仍然無法正常工作。在調試過程中,我可以看到正確的數據從控制器內部放置在ViewModel內部,但View的行爲就像它永遠不會得到它。使用quickwatch,我可以看到數據在現場。

它會顯示它的使用在LabelFors變量的名稱,但它永遠不會顯示在文本框中輸入變量的值。

查看

@model Project1.ViewModels.OrderNoLocationViewModel 

@{ Html.EnableClientValidation(); } 
@using (Html.BeginForm()) 
{ 
@Html.AntiForgeryToken()  
    <table class="item-display" style="width: 100%;"> 
     <tr> 
      <td class="label"> 
       <div class="editor-label">@Html.LabelFor(model => model.Shipper):</div> 
      </td> 
      <td class="value"> 
       <div class="editor-field"> 
        @Html.TextBoxFor(model => model.Shipper) 
        @Html.ValidationMessageFor(model => model.Shipper) 
       </div> 
      </td> 
    </table> 
} 

控制器

 [HttpPost] 
     [ValidateAntiForgeryToken()] 
     public ActionResult Index(OrderNoLocationViewModel model, string consigneeFilter, string orderNoFilter, string button) 
{ 
    model = new OrderNoLocationViewModel() 
       { 
        Shipper = "Ray" 
       }; 

       return View(model); 
} 

我有什麼事沒有世俗的想法......我有工作的其他網頁,這是字面上是像個唯一頁面這個。

請幫忙! :(

編輯:

路線

public static void RegisterRoutes(RouteCollection routes) 
     { 
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

      routes.MapRoute(
       "Default", // Route name 
       "{controller}/{action}/{id}", // URL with parameters 
       new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults 
      ); 
     } 
+0

您正在傳遞僅具有Carrier屬性集的OrderNoLocationViewModel()的新實例。由於您尚未提供此視圖模型類的代碼,因此我們無法確定此處是否設置了託運人屬性。 – failedprogramming 2014-10-16 21:31:20

+0

由於某種原因,你有意使用不同的變量名嗎?控制器中的載體,視圖中的發貨人。 – guildsbounty 2014-10-16 21:31:21

+0

您正在設置控制器中的「載體」,但「託運人」是視圖中的表單字段,所以對於您當前的代碼,我不希望看到任何內容。 – 2014-10-16 21:31:22

回答

1

它不是完全清楚你正試圖在這裏做什麼或你爲什麼做這種方式如果要顯示一個表單來編輯。的OrderNoLocationViewModel屬性然後最初與一個GET方法

public ActionResult Index() 
{ 
    var model = model = new OrderNoLocationViewModel(); 
    model.Shipper = "Ray"; 
    return View(model); 
} 

文本框現在將顯示「雷」中顯示它。

當你郵寄回

[HttpPost] 
public ActionResult Index(OrderNoLocationViewModel model) 
{ 
} 

model.Shipper將包含無論是在文本框(這將是「雷」如果用戶沒有改變的值)的值。

重新分配模型您在POST方法

model = new OrderNoLocationViewModel() 
{ 
    Shipper = "Ray" 
}; 
return View(model); 

這裏做有沒有影響,除非你明確ModelState(視圖從ModelState採用的值)。我認爲在你的案件Shipper初始值是nullstring.Empty返回視圖,這樣的情況下,其仍nullstring.Empty要看到這項工作,修改POST方法

[HttpPost] 
public ActionResult Index(OrderNoLocationViewModel model) 
{ 
    ModelState.Clear(); 
    model.Shipper = "Some other value"; 
    return View(model); 
} 

文本框現在將包含「其他一些價值」。 但是,這並不是您真正想要做的事情,因爲清除ModelState也會刪除所有驗證錯誤以及

相關問題