【问题标题】:Using a WebGrid in MVC3在 MVC3 中使用 WebGrid
【发布时间】:2014-01-04 22:19:22
【问题描述】:

我是 ASP.NET MVC3 的新手,并且拼命尝试让一些简单的工作。我觉得我正在尝试做一些非常简单的事情。但是,我无法让基本网格正常工作。我在 Visual Studio 中使用默认设置,这就是我所做的:

HomeController.cs

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Welcome to ASP.NET MVC!";

        List<Person> test = new List<Person>();
        test.Add(new Person("John", "Smith"));
        test.Add(new Person("Bill", "Torr"));

        return View(test);
    }

    public ActionResult About()
    {
        return View();
    }
}

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Person(string firstName, string lastName)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
    }
}

Index.cshtml @{ ViewBag.Title = "主页"; }

<h2>@ViewBag.Message</h2>
<p>
@{
    var grid = new WebGrid(@Model);
    grid.GetHtml();    
}
</p>

奇怪的是,没有为 WebGrid 打印任何内容。我期待两行。相反,我一无所获。我做错了什么?

【问题讨论】:

    标签: asp.net-mvc-3


    【解决方案1】:

    您忘记强输入视图并将GetHtml 方法的结果输出到视图输出流。给你:

    @model IEnumerable<Person>
    
    <h2>@ViewBag.Message</h2>
    @{
        var grid = new WebGrid(Model);
    }
    
    <p>@grid.GetHtml()</p>
    

    注意@grid.GetHtml() 是如何从代码部分外部化的,这基本上是将网格 HTML 写入输出流。在您的示例中,您在代码部分中调用了grid.GetHtml(),但您没有对结果做任何事情,例如输出它们。这就是他们被遗忘的原因。

    【讨论】:

    • 但我无法在 .cshtml 文件中引用 Person。如果我尝试 @model IEnumerable 也没有任何显示。
    • @Villager,当然可以参考。只需提供它的完整命名空间@model IEnumerable&lt;YourAppName.Models.Person&gt;。或者更好的是,将此命名空间添加到您的~/Views/web.config 文件的&lt;namespaces&gt; 部分,这样您就不必在所有视图中重新执行此操作。
    • @Villager,太好了,您还有什么想问的吗?或者我们是否可以将此主题视为已关闭,在这种情况下您应该毫不犹豫地标记答案?
    【解决方案2】:

    试试这个也展示如何在 mvc3 中使用 webgrid 和 ajax http://www.helpnshareidea.in/2014/01/webgrid-in-mvc3-using-ajax.html

    【讨论】:

      猜你喜欢
      • 2013-07-11
      • 2012-02-18
      • 1970-01-01
      • 2012-05-26
      • 2011-06-20
      • 1970-01-01
      • 2012-05-22
      • 2012-05-05
      • 2012-12-01
      相关资源
      最近更新 更多