【发布时间】:2014-09-08 15:07:54
【问题描述】:
我正在设计一个组件来从 xml 文件中获取值并将其显示在下拉列表中。
但我无法将数据绑定到下拉列表。它抛出object null reference error。
型号代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Xml.Linq;
namespace WC.Models
{
public class SubjectModel
{
public IEnumerable<SelectListItem> _environmentName;
[DisplayName("EnvironmentName")]
public IEnumerable<SelectListItem> EnvironmentName
{
get
{
if (_environmentName == null)
_environmentName = new List<SelectListItem>();
return _environmentName;
}
set { _environmentName = value; }
}
[DataType(DataType.MultilineText)]
public string[] filecontent
{
get;
set;
}
public string finalfile { get; set; }
}
}
我可以找到模型中加载的值。但我无法将它传递给视图。 It throws object null reference error
控制器代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Xml.Linq;
using WC.Models;
using System.Text;
using System.Runtime.InteropServices.ComTypes;
namespace WC.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult FileUpload()
{
SubjectModel model = new SubjectModel();
return View(model);
}
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase files)
{
try
{
if (Request != null)
{
HttpPostedFileBase uploadfile = Request.Files["UploadedFile"];
HttpPostedFileBase xmlFile = Request.Files["XmlFile"];
if ((uploadfile != null) && (uploadfile.ContentLength > 0) && !string.IsNullOrEmpty(uploadfile.FileName))
{
string fileName = uploadfile.FileName;
string fileContentType = uploadfile.ContentType;
byte[] fileBytes = new byte[uploadfile.ContentLength];
uploadfile.InputStream.Read(fileBytes, 0, Convert.ToInt32(uploadfile.ContentLength));
var name = "WebConfig" + ".config";
//DateTime.Now.ToString("yyyyMMddHH")
var path = Path.Combine(Server.MapPath("~/App_Data/Config/"), name);
uploadfile.SaveAs(path);
ViewData["Messageconfig"] = "config file uploaded successfully";
}
if ((xmlFile != null) && (xmlFile.ContentLength > 0) && !string.IsNullOrEmpty(xmlFile.FileName))
{
string fileName = xmlFile.FileName;
string fileContentType = xmlFile.ContentType;
byte[] fileBytes = new byte[xmlFile.ContentLength];
xmlFile.InputStream.Read(fileBytes, 0, Convert.ToInt32(xmlFile.ContentLength));
var name = "XML" + DateTime.Now.ToLongDateString() + ".xml";
//DateTime.Now.ToString("yyyyMMddHH")
var path = Path.Combine(Server.MapPath("~/App_Data/XML/"), name);
xmlFile.SaveAs(path);
ViewData["MessageXml"] = "xml file uploaded successfully";
SubjectModel model = new SubjectModel();
var xDoc = XDocument.Load(fileName);
IEnumerable<XElement> envGroups = from xmlDoc in xDoc.Descendants().Elements("environment")
select xmlDoc;
model.EnvironmentName = from envName in envGroups.Attributes("name")
select new SelectListItem
{
Text = envName.Value,
Value = envName.Value.ToString()
};
return View(model);
}
}
}
catch
{
ViewData["Message"] = "Upload failed";
return View("FileUpload");
}
return View("FileUpload");
}
public ActionResult GetFileContent()
{
SubjectModel model = new SubjectModel();
var name = "WebConfig" + ".config";
////DateTime.Now.ToString("yyyyMMddHH")
var path = Path.Combine(Server.MapPath("~/App_Data/Config/"), name);
model.filecontent = System.IO.File.ReadAllLines(path);
string content = null;
for (int i = 0; i < model.filecontent.Length; i++)
{
content = content + model.filecontent[i] + "\n";
}
model.finalfile = content;
return View("FileUpload", model);
}
public ActionResult GeneratePage(string name)
{
return View("GeneratePage");
}
}
}
在下拉列表的地方它会抛出错误。检查一下。
**查看代码:**
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<WC.Models.SubjectModel>" %>
<!DOCTYPE html>
<html>
<head id="Head1">
<title>Index</title>
<script language="javascript" type="text/javascript">
</script>
</head>
<body>
<script type="text/jscript">
function setText() {
document.getElementById('txtFile').value = 'model.finalfile';
}
</script>
<%using (Html.BeginForm("FileUpload","Home", FormMethod.Post));%>
<form id="form1" runat="server" method="post" enctype="multipart/form-data">
<div>
<br />
<br />
<br />
<input name="UploadedFile" type="file" id = "UploadFile" />
<input type="submit" name="Submitconfig" value="Upload Config File" />
<br />
<font color="green"> <%: ViewData["Messageconfig"] %> </font>
<br />
<br />
<input name="XmlFile" type="file" />
<input type="submit" name="SubmitXML" value="Upload XML File" />
<br />
<font color="green"><%: ViewData["MessageXml"] %> </font>
<br />
<br />
<br />
<asp:Label ID="lblEnvName" runat="server" Text="Environment Name"></asp:Label>
<%=Html.DropDownListFor(m => m.EnvironmentName,Model.EnvironmentName)%>
<br />
<br />
<%= Html.ActionLink("click", "GetFileContent", "Home")%>
<%-- <br />
<input type ="submit" id = "btnFile" value =" View File" onclick="setText" />
<br />
<br />--%>
<br />
<br />
<%= Html.TextAreaFor(m => m.finalfile, 100, 100, new { style = "size:2" })%>
<br />
<br />
<%-- <asp:TextBox ID="txtFile" runat="server" TextMode="MultiLine" ></asp:TextBox>--%>
<br />
<br />
<%= Html.ActionLink("GeneratePage", "GeneratePage")%>
<%-- <%= Html.TextAreaFor(Model => Model.finalfile, 100, 100, new { style = "size:2" })%>--%>
<%-- <asp:Button ID="btnPage" runat="server" Text="Generate Page" />--%>
<br />
<br />
</div>
</form>
</body>
</html>
当我尝试upload config error 时出现此错误。请帮助我。
【问题讨论】:
-
你能把代码减少到必要的最小值吗?
-
从我在代码中看到的,表达式 m.EnvironmentName,Model.EnvironmentName)%> 有逻辑问题。您正在尝试绑定作为 SelectListItem 集合的模型属性。您需要创建一个单独的属性(例如 public string SelectedEnvironmentName { get;set;} )并在您的表达式中使用它,如下所示: m.SelectedEnvironmentName ,Model.EnvironmentName)%>
-
谢谢你..我会试一试...
-
我仍然遇到同样的错误。当我尝试上传配置文件时,它会抛出“对象引用未设置为对象的实例。”在这一行: m.SelectedEnvironmentName ,Model.EnvironmentName)%>