无法使用asp MVC将XML文件中的值绑定到下拉列表

时间:2014-09-08 15:07:55

标签: asp.net-mvc asp.net-mvc-3

我正在设计一个组件来从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>
            &nbsp;&nbsp;&nbsp;
    <%=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时,我收到此错误。请帮助我。

Error Image Screen shot 1 Error Image Screen shot 2

2 个答案:

答案 0 :(得分:0)

<强>更新

您的视图中有两个表单。

更正您的查看代码。如下......

<% using (Html.BeginForm("FileUpload", "FileUpload", 
                    FormMethod.Post, new { enctype = "multipart/form-data" }))
        {%>
        <input name="UploadedFile" type="file" id="UploadedFile" />
        <input type="submit" name="Submitconfig" value="Upload Config File" />
<%} %>

     <% using (Html.BeginForm("FileUpload", "FileUpload", 
                    FormMethod.Post, new { enctype = "multipart/form-data" }))
        {%>
        <input name="XmlFile" type="file" id="XmlFile" />
        <input type="submit" name="SubmitXML" value="Upload XML File" />
<%} %>

<强>校正:

  1. 删除您提到的表单代码。并粘贴上面的代码。
  2. <form id="form1" runat="server" action="Here You go" method="post" enctype="multipart/form-data">

    <%using (Html.BeginForm("FileUpload","Home", FormMethod.Post));%>

    1. 阅读此简单文件从Code Project
    2. 上传其工作原理

      DropDownList正常工作:

      您需要使用DropDownList而不是DropDownListFor

      代码如下:以下代码运行正常。

      <%=Html.DropDownList("EnvironmentName", new SelectList(Model.EnvironmentName, "Value" , "Text")) %>     
      

      如需更多参考,请查看此link

答案 1 :(得分:-1)

try
{
    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";
        List<SelectListItem> objvalue = new List<SelectListItem>();
        objvalue.Add(new SelectListItem
                                {
                                    Text = "--Select --",
                                    Value = "-1"
                                });
        model.EnvironmentName = objvalue;  
    }

    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";


        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()
                               };                                                                  
    }
}
catch
{
    ViewData["Message"] = "Upload failed";
    return View(model);
}
return View(model);