Html.DropDownListFor没有选择正确的对象

时间:2017-02-27 08:43:11

标签: html asp.net-mvc razor dropdown html.dropdownlistfor

查看

@Html.DropDownListFor(model => model.ObjectId, 
     Model.SelectListItems, 
     "Default", 
     new { @id = "DropDown" })

控制器

TheViewModel model = ((TheViewModel )Session[nameof(TheViewModel )]);
if (model == null)
{
    // fill model with data
}
return View(model);

我从会话加载viewmodel,现在想要通过id(来自模型)设置所选值,但它不能以这种方式工作。 但是在post方法中,我在我的模型中获得了正确的信息,当我从会话中加载数据时也是一切设置。

请注意我不想使用viewbag

两个变量都在控制器中设置。 ObjectId是一个int

提前谢谢。

1 个答案:

答案 0 :(得分:0)

请试试这个:

型号:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Testy20161006.Models
{
    public class AnItem
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }


    public class TheViewModel
    {
        public TheViewModel()
        {
            items.Add(new AnItem { Id = 1, Name = "dh1" });
            items.Add(new AnItem { Id = 2, Name = "dh2" });
            items.Add(new AnItem { Id = 3, Name = "dh3" });
        }

        public string SelectedValue { get; set; }

        public List<AnItem> items = new List<AnItem>();

        public IEnumerable<SelectListItem> Items
        {
            get { return new SelectList(items, "Id", "Name"); }
        }
        public string RequiredValidationMessage { get; set; }
    }
}

控制器:

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult Index26(TheViewModel m)
    {
        var selectedText = m.SelectedValue;
        return View(m);
    }

    public ActionResult Index26()
    {
        TheViewModel m = new TheViewModel();
        return View(m);
    }

查看:

@model  Testy20161006.Models.TheViewModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index26</title>
</head>
<body>
    <div>
        @using (Html.BeginForm())
        {
            @Html.LabelFor(m => m.SelectedValue)
            @Html.DropDownListFor(m => m.SelectedValue,
        new SelectList(Model.Items, "Value", "Text"))

            <input type="submit" value="Get Value of dropdown" />
        }
    </div>
</body>
</html>