如何在MVC中显示国家/地区列表 [英] How to display countries list in MVC

查看:93
本文介绍了如何在MVC中显示国家/地区列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在vs 2010.in中有一个mvc应用程序,我有一个带有一个方法Index()的家庭控制器。它将返回一个国家列表。我希望通过视图显示哪些国家/地区列表。如何在vs 2010中做到这一点。请告诉我如何为此添加视图以及我们需要编写代码以便将其显示给最终用户。





这是我的控制器动作。



公共ActionResult索引()

{

ViewData [countries] =新列表< string>()

{

INDIA,

PAKISTHAN,

AUSTRALIA,

南非

};

返回查看();

}

I have a mvc application in vs 2010.in that i have a home controller with one method Index().It is going to return a list of countries.That countries list i want to display through view. How to do that in vs 2010.please tell me how to add view for this and what we need to write code for displaying it to end user.


Here is my controller action.

public ActionResult Index()
{
ViewData["countries"]= new List<string>()
{
"INDIA",
"PAKISTHAN",
"AUSTRALIA",
"SOUTH AFRICA"
};
return View();
}

推荐答案

而是为国家/地区创建模型,然后返回该模型进行查看。



//型号

Rather create the Model for the country, and return that model to view.

// Model
public class Country
{
    public int ID { get; set; }
    public string Name { get; set; }
}



//控制器


// Controller

public ActionResult Index()
{
    List<country> countries = new List<country>() {
        new Country() { ID = 1, Name = "India"},
        new Country() { ID = 2, Name = "Pakistan"},
        new Country() { ID = 3, Name = "Australia"},
        new Country() { ID = 4, Name = "South Africa"}
    }
    return View(countries);
}</country></country>



//查看


// View

@model IEnumerable<country>
<ul>
    @foreach(var item in Model)
    {
        <li id="@item.ID">@item.Name</li>
    }
</ul></country>



这是在MVC中如何做到这一点的基本思路,你可以根据需要改变它。 :)



[评论后更新]

// controller


This is the basic idea how you can do it in MVC, you can change this according to your need. :)

[Updates after the comments]
// controller

IEnumerable<string> list = new List<string><br />
{<br />
"INDIA",<br />
"PAKISTHAN",<br />
"AUSTRALIA",<br />
"SOUTH AFRICA"<br />
};<br />
ViewData["countries"] = list;<br />
<br />
// view<br />
@foreach (string item in ViewData["countries"] as List<string>)<br />
{<br />
<p>@item</p><br />
}

< br $> b $ b

-KR



-KR


这篇关于如何在MVC中显示国家/地区列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆