开发者

Loading multiple controls in ASP.NET MVC

I am creating my first site in asp.net MVC and I have a very beginner question in my mind. i have seen that in controller we are returning the actionview for what we want to display in the page [Most of the example in the websites I can see they are only d开发者_StackOverflow中文版isplaying the content in the page] . What if I have to load 3 drop down list, 2 tables , 2 radio buttons etc. What is the best practice and the correct way to load these many controls on the page?


Chris

It sounds like you are expecting to use controls like one does in ASP.Net Web Forms. However, with MVC the View consists of standard HTML. The controls you mention can just be input select and so on. There are various helper classes and methods that you can use in the view to help you render the HTML you need - In particular take a look at the Razor syntax.

I'd start with looking at a couple of examples, and it should be clearer.... Here's a good one: http://www.nerddinner.com/ (source code here http://nerddinner.codeplex.com/) Maybe pick up a couple of books from Amazon as well.

HTH

Phil


The examples you typically see use MVC's scaffolding, which creates a very simple Controller/Actions/Views to manipulate a certain Model class. But you're free to show anything you want in your pages. Here's an example on how to show a drop down list.

First create an object that will hold all the stuff you want to display on the page:

public class GameDetailsViewModel
{
    public Game Game { get; set; }
    public SelectList Players { get; set; }
}

Note the SelectList. It will be used as the source for the DropDownList.

Then the Action fills in this object:

public ViewResult Details(int id)
{
    GameDetailsViewModel viewModel = new GameDetailsViewModel();
    viewModel.Game = db.Games.Single(g => g.ID == id);

    IEnumerable<Player> players = db.Players();
    viewModel.Players = new SelectList(players, "ID", "FullName");

    return View(viewModel);
}

Note the overload to the View() method, that takes the object we created to package the stuff we need on the page.

Then on the View, you can use an HtmlHelper to render a DropDownList:

@using (Html.BeginForm("signup", "games", FormMethod.Post))
{
    @Html.DropDownList("playerID", Model.Players, "Select...", null)
    <input type="submit" value="Sign up" />
}

This is a very simple example, but you can extend it to send whatever you want to the View and then render it using plain old HTML or the handy HtmlHelpers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜