2015-10-20 56 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