【问题标题】:how to load xml node into html textboxfor如何将xml节点加载到html textboxfor
【发布时间】:2018-03-28 12:34:26
【问题描述】:

所以我制作了一个用于编辑 XML 节点的页面,但是我究竟如何将节点中的值加载到 html.textboxfor

正如我一直在尝试的那样

@Html.TextBoxFor(s => s.CarIsScrapped, new { @Value = CarIsScrapped}))

然后我明白了

CS0103:当前上下文中不存在名称“CarIsScrapped”

现在我可以显示或编辑节点,但不能同时使用,因为我要么必须使用

CarIsScrapped = node["CarIsScrapped"].InnerText = scrapped 

用于编辑,但文本框为空

CarIsScrapped = node["CarIsScrapped"].InnerText

用于显示但我无法编辑节点

我的页面

@using ActionLink_Send_Model_MVC.Models
@model IEnumerable<SettingsModel>

@{
    Layout = null;
}
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
    foreach (SettingsModel setting in Model)
    {

        <table cellpadding="0" cellspacing="0">
            <tr>
                <th colspan="2" align="center"></th>
            </tr>
            <tr>
                <td class="auto-style1">Name: </td>
                <td class="auto-style1">
                    @Html.TextBoxFor(m => setting.CarIsScrapped)
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    @Html.ActionLink("Submit", "", null, new { @id = "submit" })</td>
            </tr>
            <tr>

            </tr>
            <tr>

            </tr>
            <tr>

            </tr>
        </table>
    }
    }
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#submit").click(function () {
                document.forms[0].submit();
                return false;
            });
        });
    </script>
</body>

控制器

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index(SettingsModel setting)
    {
        List<SettingsModel> settings = new List<SettingsModel>();

        string scrapped = setting.CarIsScrapped;

        //Load the XML file in XmlDocument.
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("~/XML/Settings.xml"));

        //Loop through the selected Nodes.
        foreach (XmlNode node in doc.SelectNodes("Settings/UserSettings"))
        {
            //Fetch the Node values and assign it to Model.
            settings.Add(new SettingsModel
            {
                CarIsScrapped = node["CarIsScrapped"].InnerText = scrapped
            });
            doc.Save(Server.MapPath("~/XML/Settings.xml"));
        }
        return View(settings);
    }
}

【问题讨论】:

  • @Html.TextBoxFor(s =&gt; s.CarIsScrapped, new { @Value = CarIsScrapped})) 将导致 CS0103: The name 'CarIsScrapped' does not exist in the current context 异常 → CarIsScrapped 是一个属性名称,你不能使用它直接。
  • 我可以用 s => s.CarIsScrapped 更改值,具体怎么做

标签: c# asp.net xml razor


【解决方案1】:

不要使用 foreach,因为这会在您尝试将输入绑定回模型列表时导致问题。您需要在此处使用循环:

for (var i = 0; i < Model.Count(); i++) {
@Html.TextBoxFor(m => Model[i].CarIsScrapped)
}

【讨论】:

    【解决方案2】:

    模型绑定到列表

    问题已完全更改为新问题。这是对新问题的回答。

    将页面的模型更改为List&lt;SettingsModel&gt;。然后使用for 循环创建用于编辑模型的文本框。同样对于Post 方法,使用List&lt;SettingsModel&gt; 类型的变量。

    这是您需要使用的代码:

    @model List<SettingsModel>
    
    @using (Html.BeginForm())
    {
        for (int i = 0; i < Model.Count; i++)
        {
            <div>
                @Html.TextBoxFor(x => Model[i].CarIsScrapped)
            </div>
        }
        <input type="submit" value="Save" />
    }
    

    Phil Haack 有一篇关于 Model Binding to a List 的精彩文章。查看文章以了解有关编辑非顺序列表的更多信息。

    当前上下文中不存在名称“XXXX”

    问题已完全更改为新问题。这是对老问题的回答。

    @Html.TextBoxFor(s =&gt; s.CarIsScrapped, new { @Value = CarIsScrapped})) 显然会导致CS0103: The name 'CarIsScrapped' does not exist in the current context 异常,因为在方法的第二个参数中 (@987654328 @),名称 CarIsScrapped 未定义。实际上是一个属性名,不能直接使用。

    其实用TextBoxFor,用x =&gt; x.CarIsScrapped就够了,不需要第二个参数。

    通常当你收到当前上下文中不存在的名字时,你可以检查这些情况:

    • 您尚未使用该名称定义变量。
    • 您拼错了变量名。
    • 缺少定义类的命名空间。
    • 您的项目需要添加对包含该类型的 dll 的引用。

    在这种情况下,您将CarIsScrapped 用作变量,并且似乎该变量在当前上下文中不存在。

    正确的代码行应该是:

    @Html.TextBoxFor(s => s.CarIsScrapped)
    

    此外,在操作中,您需要将模型传递给页面,除非您会看到一个空文本框。

    【讨论】:

    • 这也是我将模型传递到页面并将其作为 @Html.TextBoxFor(s => s.CarIsScrapped) 所做的一切,它可以很好地编辑 xml 节点,但文本框仍然是空载
    • 答案试图描述异常的原因并向您展示正确的语法。然后它告诉您需要将模型传递给视图以在文本框中具有值。我看不到答案中遗漏的任何内容。如果您对答案有具体问题或疑问,请告诉我...
    • 好吧,它更新了我的问题,因为我想出了如何显示或编辑它,但我不能同时做这两件事
    • 你完全改变了问题!
    【解决方案3】:

    问题是视图上的模型是 IEnumerable。 Helpers 使用反射来确定在将 TextBox 呈现为 html 时分配给 TextBox 的前缀、名称和 ID。由于您使用的是 foreach 并遍历 IEnumerable,因此每个 TextBox 的名称和 id 将相同。查看您呈现的 HTML 并查看它们的外观。在回帖中,它们都将具有相同的名称,因此将被连接到逗号分隔值列表中。模型绑定器将无法将其反序列化为您的原始 IEnumerable 模型。看看 Request.Params

    您应该创建将 SettingsModel 列表作为 List 属性的模型,然后在 Razor 中使用索引访问器来执行 Html.TextBoxFor。如果这不是一个选项,请将您的模型设置为 List 并通过索引而不是使用 foreach 访问它。

    像这样:

    @using ActionLink_Send_Model_MVC.Models
    @model List<SettingsModel>
    
    @{
        Layout = null;
    }
    <body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        for(var idx = 0; idx < Model.Count();idx++) { 
        {
    
            <table cellpadding="0" cellspacing="0">
                <tr>
                    <th colspan="2" align="center"></th>
                </tr>
                <tr>
                    <td class="auto-style1">Name: </td>
                    <td class="auto-style1">
                        @Html.TextBoxFor(m => Model[idx].CarIsScrapped)
                    </td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td>
                        @Html.ActionLink("Submit", "", null, new { @id = "submit" })</td>
                </tr>
                <tr>
    
                </tr>
                <tr>
    
                </tr>
                <tr>
    
                </tr>
            </table>
        }
    }
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#submit").click(function () {
                document.forms[0].submit();
                return false;
            });
        });
    </script>
    </body>
    

    【讨论】:

      【解决方案4】:

      XML 文件:

      <?xml version="1.0" standalone="yes"?>
      <Customers>
      <Customer>
      <Id>1</Id>
      <Name>A.B</Name>
      <Country>INDIA</Country>
      </Customer>
      <Customer>
      <Id>2</Id>
      <Name>B.A</Name>
      <Country>India</Country>
      </Customer>
      <Customer>
      <Id>3</Id>
      <Name>Suzanne Mathews</Name>
      <Country>France</Country>
      </Customer>
      <Customer>
      <Id>4</Id>
      <Name>Web</Name>
      <Country>Russia</Country>
      </Customer>
      </Customers>
      

      命名空间 您将需要导入以下命名空间。

      using System.Xml;
      using System.Collections.Generic;
      

      型号

      以下是一个名为 CustomerModel 的模型类,具有三个属性,即 CustomerId、Name 和 Country。

      public class CustomerModel
      {
      ///<summary>
      /// Gets or sets CustomerId.
      ///</summary>
      public int CustomerId { get; set; }
      
      ///<summary>
      /// Gets or sets Name.
      ///</summary>
      public string Name { get; set; }
      
      ///<summary>
      /// Gets or sets Country.
      ///</summary>
      public string Country { get; set; }
       }
      

      控制器

      在控制器的 Index Action 方法中,使用 XmlDocument 类对象读取 XML 文件。 然后使用 XPath 查询选择客户节点,并在所有选定节点上执行循环。 在循环内部,从每个子节点中提取值并分配给模型类对象的适当属性,并准备模型类对象的通用列表集合。 最后将 Model 类对象的 Generic 列表集合返回给 View。

      public class HomeController : Controller
      {
      // GET: Home
      public ActionResult Index()
      {
          List<CustomerModel> customers = new List<CustomerModel>();
      
          //Load the XML file in XmlDocument.
          XmlDocument doc = new XmlDocument();
          doc.Load(Server.MapPath("~/XML/Customers.xml"));
      
          //Loop through the selected Nodes.
          foreach (XmlNode node in doc.SelectNodes("/Customers/Customer"))
          {
              //Fetch the Node values and assign it to Model.
              customers.Add(new CustomerModel
              {
                  CustomerId = int.Parse(node["Id"].InnerText),
                  Name = node["Name"].InnerText,
                  Country = node["Country"].InnerText
              });
          }
      
          return View(customers);
      }
      }
      

      查看

      在视图中,客户模型类被声明为 IEnumerable,它指定它将作为集合使用。 为了显示记录,使用了 HTML 表格。将在模型上执行一个循环,该循环将生成带有客户记录的 HTML 表行。

        @using Grid_XML_MVC.Models
       @model IEnumerable<CustomerModel>
      
      @{
       Layout = null;
       }
      
      
      <!DOCTYPE html>
      
      <html>
      <head>
      <meta name="viewport" content="width=device-width"/>
      <title>Index</title>
      </head>
      <body>
      <table cellpadding="0" cellspacing="0">
          <tr>
              <th>Customer Id</th>
              <th>Name</th>
              <th>Country</th>
          </tr>
          @foreach (CustomerModel customer in Model)
          {
              <tr>
                  <td>@customer.CustomerId</td>
                  <td>@customer.Name</td>
                  <td>@customer.Country</td>
              </tr>
          }
      </table>
      </body>
      </html>
      

      如果您有任何问题,请参考以下链接:

      https://www.aspsnippets.com/Articles/Read-and-display-XML-data-in-View-in-ASPNet-MVC-Razor.aspx

      【讨论】:

      • 确实给了我一个 'System.Collections.Generic.IEnumerable一个初始的“System.Collections.Generic”类型参数。当使用@using ActionLink_Send_Model_MVC.Models @model IEnumerable&lt;SettingsModel&gt;
      猜你喜欢
      • 1970-01-01
      • 2020-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多