ASP.net MVC将一些数据从视图传递给控制器

时间:2013-03-22 19:37:25

标签: c# asp.net-mvc view controller

在视图中我有ListBox,因此用户可以选择一些数据。出于同样的原因,我也有MultiSelectList。 用户可以从MultiSelectList中选择一些日期,或者他没有必要(他可以将该字段留空)。这很好。 我决定添加TextBox,以便用户可以根据需要输入数据。现在,当用户向TextBox输入数据并且没有从MultiSelectList中选择任何数据时,一切都很好。

但是!如果用户从MultiSelectList中选择数据并将TextBox留空,则会收到以下错误:

The ViewData item that has the key 'CompetitionId' is of type 'System.Int32' but must be       of type 'IEnumerable<SelectListItem>

LisBox显示了该错误。

我对另一个视图/控制器有同样的问题。我已启用用户上传图片的选项,如果他没有点击选择图片,并上传图片,我会在该视图中为另一个ListBox获得相同的错误。

请帮我解决这个问题。这是第一个控制器/视图的代码

控制器:

[Authorize]
    public ActionResult Create()
    {
        ViewBag.Competitions = new SelectList(_competitionRepository.GetAllCompetitionsAndNotActive().AsEnumerable(),
                                              "CompetitionId", "Name");
        ViewBag.Tags = new MultiSelectList(_tagRepository.GetAllTags().AsEnumerable(), "TagId", "Name");



        return View();
    }

    //
    // POST: /Advert/Create

    [HttpPost, Authorize]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(AdvertDTO advertDTO, int [] tags, int competitionId, string inputTags)
    {
        if (ModelState.IsValid)
        {

查看:

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
    <legend>Advert</legend>


    <div class="editor-label">
        Choose Competition
    </div>
    <div class="editor-field">
        @Html.DropDownList("CompetitionId", (SelectList)ViewBag.Competitions, new { @class = "chzn-select", data_placeholder = "Choose  Competitions...", style="width:350px;" } )           
        @Html.ValidationMessageFor(model => model.CompetitionId)
    </div>      
    ....     
    @Html.ListBox("Tags", (MultiSelectList)ViewBag.Tags, new { @class = "chzn-select", data_placeholder = "Choose  Tags...", style="width:350px;" })


       <br/>
       <label>OR</label>
       <input type="text" id="inputTags" name="inputTags" style="width: 325px" />

    <p>
        <input type="submit" value="Create"  />
    </p>
</fieldset>

}

修改 长话短说我希望用户能够提交空白字段

3 个答案:

答案 0 :(得分:0)

我认为这条线路不好

 @Html.ValidationMessageFor(model => model.CompetitionId)

你能评论一下吗?

答案 1 :(得分:0)

我认为您的操作实际上是从选择列表中回发所有值。如果您只想回发所选项目,可以尝试类似

的内容
Html.DropDownListFor(model => model.CompetitionId, (SelectList)ViewBag.Competitions, new { @class = "chzn-select", data_placeholder = "Choose  Competitions...", style="width:350px;" } )

答案 2 :(得分:0)

我已经解决了......我没有看到几个愚蠢的错误:/抱歉所有的麻烦