1

I am new to ASP.NET MVC 3. I am trying to create a basic WebGrid to try and learn how this works. Currently, I have the following code:

@{
    ViewBag.Title = "Home Page";
}

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

When I run this code, I receive an error that says: "A data source must be bound before this operation can be performed.". My question is, how do I bind this WebGrid to some client-side JSON. I don't have a back-end database. I'm just trying to learn about the WebGrid without having to wireup a database.

thanks!

1 Answer 1

2

As always in an ASP.NET MVC application you start with a view model:

public class MyViewModel
{
    public int Foo { get; set; }
    public string Bar { get; set; }
}

then a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new[]
        {
            new MyViewModel { Foo = 1, Bar = "bar 1" },
            new MyViewModel { Foo = 2, Bar = "bar 2" },
            new MyViewModel { Foo = 3, Bar = "bar 3" },
        };
        return View(model);
    }
}

and finally a corresponding view (~/Views/Home/Index.cshtml):

@model IEnumerable<MyViewModel>
@{
    var grid = new WebGrid(Model);
}
@grid.GetHtml()

So as you can see the data source of the grid is actually the view model that the controller populated and passed to the view. The actual data could come from anywhere. It's the controller's responsibility though to populate the view model and pass it to the view.

And to learn more about the WebGrid control you may take a look at the following article. And here's another one.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.