如何将xml节点加载到html textboxfor中

时间:2018-03-28 12:34:26

标签: c# asp.net xml razor

所以我创建了一个用于编辑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);
    }
}

4 个答案:

答案 0 :(得分:1)

模型绑定到List

  

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

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

以下是您需要使用的代码:

@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 => s.CarIsScrapped, new { @Value = CarIsScrapped}))显然会导致 CS0103:当前上下文异常中不存在名称'CarIsScrapped',因为在方法的第二个参数中new { @Value = CarIsScrapped}),未定义名称CarIsScrapped。实际上它是一个属性名称,你不能直接使用它。

实际上使用TextBoxFor,使用x => x.CarIsScrapped就足够了,不需要第二个参数。

通常当您收到该名称在当前上下文中不存在时,您可以检查以下情况:

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

在这种情况下,您使用CarIsScrapped就像一个变量,似乎这个变量在当前上下文中不存在。

正确的代码行应该是:

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

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:0)

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

您应该创建具有SettingsModel列表的Model作为List属性,然后在Razor中使用索引访问器来执行Html.TextBoxFor。如果这不是一个选项,请将您的模型设置为List并通过索引vs使用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>

答案 3 :(得分:-1)

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的Model类,它具有三个属性,即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类对象的适当属性,并准备Model类对象的Generic列表集合。 最后,Model类对象的Generic list集合返回到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);
}
}

查看

在View中,Customer Model类被声明为IEnumerable,它指定它将作为Collection提供。 为了显示记录,使用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