我试图提交一个表单,将级联下拉列表和图像的结果发布回控制器,但在使用Html.DropDownList时收到以下错误
System.InvalidOperationException: 'There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'BreedDD'.' \
当我手动写出选择时,它会抛出一个NullReferenceException
根据一些研究表明,ViewBag将失去它的值,这将解释空引用。但我还没有找到对我有用的解决方案,而且我已经到了临界点。
FileUploadController.cs
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
@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>模型
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; }
}
}发布于 2019-08-05 08:44:44
当表单在上传文件时回发时,ViewBag对象就会丢失。成功上传文件后,您将重定向回索引页。这一次,您的视图不接收DropdownList的DropdownList数据。因此,在成功上传ViewBag方法中的文件之后,需要为DropdownList设置UploadFiles,如下所示:
[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");
}https://stackoverflow.com/questions/57351558
复制相似问题