2015-10-20 61 views
1

我想在ASP.NET使用ViewBag內引號,像這樣:ASP.NET使用ViewBag引號內

@using (Html.BeginForm("Index?community=" + @ViewBag.community + "&lot=" + @ViewBag.lot + "", 
         "UploadFile", 
         FormMethod.Post, 
         new { enctype = "multipart/form-data" })) 
      { 
       <label for="file">Upload File:</label> 
       <input type="file" name="file" id="file" /><br><br> 
       <input type="submit" value="Upload File" /> 
       <br><br> 
       @ViewBag.Message 
      } 

我也曾嘗試以下操作:

@using (Html.BeginForm("[email protected]&[email protected]", 
         "UploadFile", 
         FormMethod.Post, 
         new { enctype = "multipart/form-data" })) 
      { 
       <label for="file">Upload File:</label> 
       <input type="file" name="file" id="file" /><br><br> 
       <input type="submit" value="Upload File" /> 
       <br><br> 
       @ViewBag.Message 
      } 

是否有可能在引號內使用@ViewBag?

+0

另外,你可能會發現你的生活對強類型模型更有意義。建議使用自定義視圖模型而不是凌亂的ViewBag。 https://stackoverflow.com/questions/13779294/viewmodels-or-viewbag –

回答

2

ViewBag沒有什麼特別之處,它是一個可以在任何其他頁面上下文中使用的屬性。

"Index?community=" + ViewBag.community 
+0

我得到這個錯誤:Error 'System.Web.Mvc.HtmlHelper '沒有可用的方法名爲'BeginForm',但似乎有一個這個名字的擴展方法。擴展方法不能動態分派。考慮轉換動態參數或調用擴展方法而不使用擴展方法語法。 – user979331

+0

@ user979331:有幾件事情可能會導致這種情況。它可能不喜歡「ViewBag」是「動態」的事實。試試:'((string)ViewBad.community)'而不是? – David

+0

我有點困惑。你能給我一個關於它應該如何看的例子嗎? – user979331

2

肯定:只要建立字符串,就像您在任何其他C#代碼時參考它只是刪除@既然你已經確定你在行(@using)的開頭寫的表達式。這樣做:

@using (Html.BeginForm("Index?community=" + ((string)ViewBag.community) + "&lot=" + ((string)ViewBag.lot),[...] 

無論如何,我建議使用視圖模型從控制器傳遞值來查看,而不是ViewBag。

+0

我收到此錯誤:錯誤'System.Web.Mvc.HtmlHelper '沒有名爲'BeginForm'的適用方法,但似乎具有通過該名稱的擴展方法。擴展方法不能動態分派。考慮轉換動態參數或調用擴展方法而不使用擴展方法語法。 – user979331

+0

我剛剛報告了您的示例以顯示如何使用ViewBag。我沒有測試整個代碼。但是這樣做:@using(Html.BeginForm(「Index?community =」+((string)ViewBag.community)+「&lot =」+((string)ViewBag.lot),[ – Alberto

+0

編輯答案更新的代碼和一般提示;) – Alberto