【问题标题】:How to use dropdownlistfor in mvc3 razor with model如何在带有模型的 mvc3 剃须刀中使用 dropdownlistfor
【发布时间】:2013-03-14 06:11:01
【问题描述】:

我想在我的视图中通过下拉框使用以下属性。 我怎么能 ? 我尝试了很多方法,但是
请帮忙

public IEnumerable<SelectListItem> Topic
{
    get
    {
        return  new[]
        {
            new SelectListItem { Value = "1", Text = "Science", Selected=true },
            new SelectListItem { Value = "2", Text = "History" },
            new SelectListItem { Value = "3", Text = "Physics" },
        };
    }
}

【问题讨论】:

  • 你能显示你试过的代码吗

标签: asp.net-mvc-3 c#-4.0 razor html.dropdownlistfor


【解决方案1】:

你还没有添加你的视图代码。

基本上你需要像这样在你的视图中添加一个@model

@model MySampleApplication.Models.ModelName

然后在您看来,您应该像这样访问:

@Html.DropdownListFor(m=>m.Topic, Model.Topic)

DropDownListFor with ASP.NET MVC 来自斯科特·艾伦

希望对你有帮助


编辑

假设你的模型类是这样的:

public class MyModel
{
public IEnumerable<SelectListItem> Topic
{
    get
    {
        return  new[]
        {
            new SelectListItem { Value = "1", Text = "Science", Selected=true },
            new SelectListItem { Value = "2", Text = "History" },
            new SelectListItem { Value = "3", Text = "Physics" },
        };
    }
}
}

试试这样:

public ActionResult Index() 
{
   MyModel model=new MyModel();
   return View(model);
}

【讨论】:

  • 请出示您的控制器代码。您是否实例化了您的模型类并将该对象传递给您的视图?
  • 我没有。我的控制器就像 public ActionResult Index() { retuer View() } 但我的模型在 Get 中有数据。我认为它应该工作..困惑请帮忙。
  • 我可以看到数据。即使我尝试过一个示例应用程序,它也能完美运行。尝试调试并检查您的主题属性是否填充了模型对象中的下拉值
【解决方案2】:

试试这个

型号

public SelectList Topic
            {
                get
                {
                    return new SelectList(
                      new List<SelectListItem> {
                      new SelectListItem { Value = "1", Text = "Science", Selected = true },
                      new SelectListItem { Value = "2", Text = "History" },
                      new SelectListItem { Value = "3", Text = "Physics" }
                    },"Value","Text"
                    );
                }
            }


public int selectedType {get;set;}

查看

@Html.DropDownListFor(model => model.selectedType , Model.Topic)

【讨论】:

  • 感谢亲爱的回复,但它给出了同样的错误 System.NullReferenceException: Object reference not set to an instance of an object.
  • 你能显示控制器代码吗?您是否将模型作为返回视图(模型)传递给视图?
  • 不,我什么都没通过。实际上它是我的控制器的创建操作。我只想在下拉列表中绑定预定义数据。
  • 如果您希望我们为您提供帮助,您应该提供更多详细信息,例如您的视图标记和控制器代码。
  • 其实我只是想在 Dropdownlist 中使用下面提到的模型我在这里有 get 属性所以不需要从控制器获取数据 public SelectList Topic { get { return new SelectList( new List {新的 SelectListItem { Value = "1", Text = "Science", Selected = true }, new SelectListItem { Value = "2", Text = "History" }, new SelectListItem { Value = "3", Text = "Physics" } } ); } }
猜你喜欢
  • 2011-05-28
  • 1970-01-01
  • 1970-01-01
  • 2012-06-23
  • 2011-08-07
  • 1970-01-01
  • 1970-01-01
  • 2018-07-02
  • 2011-11-28
相关资源
最近更新 更多