0

I'm working on an Asp.net MVC5 application.

I need to write some XML into a textarea, so it could be parsed by some JavaScript later in my project. As of now I have loaded the XML info into a ViewBag and was wondering how I could dynamically set a textarea with this information.

my controller (Index):

        XmlDocument doc = new XmlDocument();
        doc.Load("C:\\Tasks.xml");
        ViewBag.xml = doc.InnerXml();

Thanks, any help will be greatly appreciated.

tereško
  • 58,060
  • 25
  • 98
  • 150
Stephen Sugumar
  • 545
  • 3
  • 9
  • 35
  • Do you want to edit and save the XML after you show it in the ` – Lukas G Jul 22 '14 at 15:42
  • Just need it to show there, I will using it as a load, so every time a user reloads (including first load) the info to be displayed will be read from the textarea – Stephen Sugumar Jul 22 '14 at 16:58

1 Answers1

4
-- html form

    @Html.TextArea("xml")
    <input type="submit" value="Save" />

-- html form

post action

[HttpPost]
public Actionresult SomeAction(string xml){...}

better solution (using strongly typed views)

model

public class XmlViewModel
{
    public string Xml { get; set; }
} 

controller

public Actionresult SomeAction()
{
    XmlDocument doc = new XmlDocument();
    doc.Load("C:\\Tasks.xml");
    var model = new XmlViewModel
    {
        Xml = doc.InnerXml();
    }

    return View(model);
}

[HttpPost]
public Actionresult SomeAction(XmlViewModel model)
{
    ...       

    return View(model);
}

view

@model XmlViewModel 

-- html form

    @Html.TextAreaFor(x => x.Xml)
    <input type="submit" value="Save" />

-- html form
AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197
  • Thanks, ill try implementing the better approach using the Model. one question, Why do I need the helper function in a form? – Stephen Sugumar Jul 22 '14 at 13:56
  • You dont need to use helpers, this is an optional, of course you can use pure html ( – AliRıza Adıyahşi Jul 22 '14 at 14:00
  • I understand the use of helpers, I meant to say, why do i have to put the @Html.textareafor inside of a form? Also, how would I add an ID to this textarea? – Stephen Sugumar Jul 22 '14 at 14:01
  • You dont have to use helpers, if use @HtmlTextAreaFor(x=>x.Xml) then your textarea id will be "Xml", you can see it in your page source. you can set it manually, too. Read some article about html helpers... – AliRıza Adıyahşi Jul 22 '14 at 19:40