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.

2
  • Do you want to edit and save the XML after you show it in the <textarea> or do you need it just to be shown there? Commented Jul 22, 2014 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 Commented Jul 22, 2014 at 16:58

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, ill try implementing the better approach using the Model. one question, Why do I need the helper function in a form?
You dont need to use helpers, this is an optional, of course you can use pure html (<textarea>). You need to set the name and id attribute of textarea with the model property name. HtmlHelpers are have more elegant syntax. There is no difference.
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?
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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.