【问题标题】:How to Use Html.Listboxfor and Html.Beginform如何使用 Html.Listboxfor 和 Html.Beginform
【发布时间】:2017-05-06 16:43:10
【问题描述】:

我正在尝试填充列表框并将所选选项解析回控制器。问题是我似乎无法弄清楚 BeginForm 和 Listboxfor。网上找到的教程只会让我更加困惑。

这是我的csHtml:

@Html.BeginForm("BtnSelectPost", "TimelinePageController")
    {
        <div>
             <select id="s1" class="timeline" size="20" name="Options">
                    @foreach (var C in Model)
                    {
                        Html.ListBoxFor(?)
                    }
             </select>
        </div>
    }

这是我的控制器:

        public List<Contribution> Contriblist = new List<Contribution>();
    // GET: TimelinePage
    public ActionResult TimelinePage(Event Event)
    {        
        Contriblist = DatabaseGetContribution.GetContributions(Event.ID);
        return View(Contriblist);
    }

        public SelectList GetAllContrib()
    {
        SelectList Contribslist = new SelectList(Contriblist, "ID", "Text");
        return Contribslist;
    }

我需要做什么才能让它工作?

任何帮助都会很棒

编辑: 我很抱歉缺乏信息: 我正在使用 2 个模型。 贡献:

    public int ID { get; set; }
    public int ContributionID { get; set; }
    public DateTime DateTime { get; set; }    
    public string Category { get; set; }
    public int Likes { get; set; }
    public int Reports { get; set; }    
    public int PostID { get; set; }
    public byte[] File { get; set; }
    public string Attachment { get; set; }
    public Message Message { get; set; }

    /// <summary>
    /// Create Constructor
    /// </summary> 
    /// <param name="category">The category of a post</param>    
    /// <param name="likes">The amount of likes of a post</param> 
    /// <param name="file">The file belonging to the post</param>
    /// <param name="postID">This is the ID of the post reacted to</param>
    public Contribution(DateTime datetime, string category, int likes, int reports, int postid, Message message)
    {           
        this.Category = category;    
        this.Likes = likes;
        this.Reports = reports;
        this.PostID = postid;
        this.DateTime = datetime;
        this.Message = message;
    }

和 ViewModelContrib:

public IEnumerable<SelectListItem> contrib { get; set; }

contribution 中的值取自数据库,Event 仅用于获取 ID 以检查应从数据库中获取哪些贡献。

感谢大家的帮助。

【问题讨论】:

  • 你的型号是什么?您绑定到什么属性?您在哪里将SelectList 返回到视图中? (并从 GET 方法中删除您的 Event Event 参数)
  • 您的模型甚至不包含列表框可以绑定到的属性
  • Html.DropDownListFor(, new SelectList(, "", ""))

标签: c# asp.net-mvc razor html.beginform html.listboxfor


【解决方案1】:

仅以将数据绑定到listview 并提交表单为例

首先创建一个Model类和DbContext

    public class Country
    {
        public int CountryId { get; set; }
        public string CountryName { get; set; }

    }

    public class ConuntryContext : DbContext
    {
        public virtual DbSet<Country> Country { get; set; }
    }

下一步创建控制器

public class TestController : Controller
    {
        ConuntryContext db = new ConuntryContext();

        public ActionResult Index()
        {
            db.Country.Add(new Country { 
                CountryId = 1,
                CountryName = "India"
            });

            db.Country.Add(new Country
            {
                CountryId = 2,
                CountryName = "USA"
            });

            db.Country.Add(new Country
            {
                CountryId = 3,
                CountryName = "UK"
            });

            db.SaveChanges();

            var countries = db.Country.ToList();
            ViewBag.countries = new SelectList(countries, "CountryId", "CountryName");
            return View();
        }

        [HttpPost]
        public ActionResult Action(Country country)
        {
            var countries = db.Country.ToList();
            ViewBag.countries = new SelectList(countries, "CountryId", "CountryName");
            ViewBag.selectedValue = db.Country.Where(a => a.CountryId == country.CountryId).Select(a => a.CountryName).SingleOrDefault();
            return View();
        }
}

最后创建视图

@using (Html.BeginForm("Index", "Test", FormMethod.Post))
{

    @Html.ListBox("CountryId", (SelectList)ViewBag.countries)
    <br/>
    <button type="submit">Submit</button>
}
<p>You have selected @ViewBag.selectedValue Country</p>

【讨论】:

    【解决方案2】:

    这里有一个解决方案 将属性添加到您的类或 ViewModel

    public IEnumerable<SelectListItem> YourPropertyName{get;set;}
    

    然后在你的控制器中绑定列表框的值 那么在你看来

    @Html.BeginForm("BtnSelectPost", "TimelinePageController")
        {
            <div>
                 @Html.ListBoxFor(m=>m.ModelPropertyYouWantToBindTo,Model.YourPropertyName)
            </div>
        }
    

    就是这样。列表框现在应该显示值

    【讨论】:

    • 那甚至不会编译。
    • 我向您保证,您从未使用过该代码。 ListBoxFor() 没有重载,只有 1 个参数。你甚至错过了领先的@,这意味着它无论如何都不会渲染任何东西
    • 不是,不是。 SelectList 和绑定到的属性不能相同。第二个参数需要是IEnumerable&lt;SelectListItem&gt;
    • 感谢您的快速响应,但使用此代码时出现此错误:传入字典的模型项的类型为 'System.Collections.Generic.List`1[MvcApplicationEvents.Models.Contribution ]',但此字典需要“MvcApplicationEvents.Models.ContribViewModel”类型的模型项。
    • BartSelten 在您的视图中更改您的 using 语句,它应该类似于 @model IEnumerable
    猜你喜欢
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 2012-05-10
    相关资源
    最近更新 更多