首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >邮政SelectList零

邮政SelectList零
EN

Stack Overflow用户
提问于 2019-08-05 02:19:34
回答 1查看 527关注 0票数 1

我试图提交一个表单,将级联下拉列表和图像的结果发布回控制器,但在使用Html.DropDownList时收到以下错误

System.InvalidOperationException: 'There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'BreedDD'.' \

当我手动写出选择时,它会抛出一个NullReferenceException

根据一些研究表明,ViewBag将失去它的值,这将解释空引用。但我还没有找到对我有用的解决方案,而且我已经到了临界点。

FileUploadController.cs

代码语言:javascript
复制
using Microsoft.Ajax.Utilities;
using ShipleySwine;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace UploadingFilesUsingMVC.Controllers
{
    public class FileUploadController : Controller
    {
        private ShipleySwineContext db = new ShipleySwineContext();
        // GET: FileUpload    
        public ActionResult Index()
        {
            var breedlist = db.Boars.ToList();
            var list = breedlist.Distinct();
            var list2 = list.DistinctBy(e => e.Breed).ToList();
            List<SelectListItem> breedDDsli = new List<SelectListItem>();
            new SelectList(list2);
            foreach(var item in list2)
            {
                breedDDsli.Add(new SelectListItem
                {
                    Text= item.Breed,
                    Value = item.Breed
                });

                Debug.WriteLine(item.Breed);
            }
            ViewBag.breedDD = breedDDsli;

            return View();
        }
        [HttpPost]
        public ActionResult UploadFiles(string incomingbreed, string NameNoSpaces, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                try
                {


                    if (file != null)
                    {
                        string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));
                        file.SaveAs(path);

                    }
                    ViewBag.FileStatus = "File uploaded successfully.";
                }
                catch (Exception)
                {

                    ViewBag.FileStatus = "Error while file uploading.";
                }

            }
            return View("Index");
        }

        public ActionResult getBoarsList(string boarbreed)
        {
            var breedlist = db.Boars.Where(breed => breed.Breed == boarbreed).ToList();
            var list = breedlist.Distinct();
            var list2 = list.DistinctBy(e => e.Name).ToList();
            List<SelectListItem> boarsDD = new List<SelectListItem>();
            new SelectList(list2);
            foreach (var item in list2)
            {
                boarsDD.Add(new SelectListItem
                {
                    Text = item.NameNoSpaces,
                    Value = item.NameNoSpaces
                });

                Debug.WriteLine(item.Breed);
            }
            ViewBag.BoarsDD = boarsDD;
            return PartialView("DisplayBoars");
        }

        //public ActionResult boarDetails(string boarName)
        //{
        //    var boarDetails = db.Boars.Where(name => name.Name == boarName);
        //    ViewBag.boarDetails = boarDetails;
        //    return(ViewBag.boar)
        //    //return PartialView("DisplayBoarDetails");
        //}
    }
}

Index.cshtml

代码语言:javascript
复制
@model ShipleySwine.Models.FileUpload
@{
                /**/


}

@using (Html.BeginForm("UploadFiles", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.DropDownList("BreedDD", (IEnumerable<SelectListItem>)ViewBag.breedDD,"-- Select Breed --", new { @class = "form-control" })
            @*<select class = "form-control" id="BreedDD" name="breed">
                <option value="">-- Select Breed --</option>
                @foreach(var item in ViewBag.BreedDD)
                {
                    <option value="@item.Text">@item.Text</option>
                }
            </select>*@
            <select class="form-control" id="BoarsDD" name="NameNoSpaces">

            </select>
            <div class="col-md-10">
                @Html.EditorFor(model => model.file, new { htmlAttributes = new { @class = "form-control", @type = "file" } })
                @Html.ValidationMessageFor(model => model.file, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Upload" class="btn btn-primary" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10 text-success">
                @ViewBag.FileStatus
            </div>
        </div>
    </div>
}

<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
    $(document).ready(function () {
        $("#BreedDD").change(function () {
            var breed = $(this).val();

            $.ajax({
                type: "post",
                url: "/FileUpload/getBoarsList?boarbreed=" + breed,
                contentType: "html",
                success: function (response) {

                    $("#BoarsDD").empty();
                    $("#BoarsDD").append(response);
                }
            })
        })

        //$("#BoarsDD").change(function () {
        //    var boar = $(this).val();

        //    $.ajax({
        //        type: "post",
        //        url: "/FileUpload/boarDetails?boarName=" + boar,
        //        contentType: "html",
        //        success: function (response) {
        //            console.log(response);
        //            console.log(response.val);
        //            $("#boarDetails").empty();
        //            $("#boarDetails").val(response);
        //        }
        //    })
        //})
    })
</script>

模型

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace ShipleySwine.Models
{
    public class FileUpload
    {
        [DataType(DataType.Upload)]
        [Display(Name = "Upload File")]
        [Required(ErrorMessage = "Please choose file to upload.")]
        public string file { get; set; }
        public string breed { get; set; }
        public string NameNoSpace { get; set; }

    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-08-05 08:44:44

当表单在上传文件时回发时,ViewBag对象就会丢失。成功上传文件后,您将重定向回索引页。这一次,您的视图不接收DropdownListDropdownList数据。因此,在成功上传ViewBag方法中的文件之后,需要为DropdownList设置UploadFiles,如下所示:

代码语言:javascript
复制
    [HttpPost]
    public ActionResult UploadFiles(string incomingbreed, string NameNoSpaces, HttpPostedFileBase file)
    {
        if (ModelState.IsValid)
        {
            try
            {


                if (file != null)
                {
                    string path = Path.Combine(Server.MapPath("~/UploadedFiles"), Path.GetFileName(file.FileName));
                    file.SaveAs(path);

                }
                ViewBag.FileStatus = "File uploaded successfully.";
            }
            catch (Exception)
            {

                ViewBag.FileStatus = "Error while file uploading.";
            }

        }

        //Add dropdown list to ViewBag
        var breedlist = db.Boars.ToList();
        var list = breedlist.Distinct();
        var list2 = list.DistinctBy(e => e.Breed).ToList();
        List<SelectListItem> breedDDsli = new List<SelectListItem>();
        new SelectList(list2);
        foreach(var item in list2)
        {
            breedDDsli.Add(new SelectListItem
            {
                Text= item.Breed,
                Value = item.Breed
            });

            Debug.WriteLine(item.Breed);
        }
        ViewBag.breedDD = breedDDsli;

        return View("Index");
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57351558

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档