Bojangles
Bojangles

Reputation: 467

XML feed from a View Model

I have two related tables in the dbContext, RunArea has many Runs. I want to generate an XML feed.

This is my view Model:

public class RunAreaViewModel
{
    public string RunName { get; set; }
    public string RunAreaName { get; set; }
}

And my controller:

public ActionResult Test()
{
    var theRuns =
        (from r in db.Runs
            join ra in db.RunAreas on r.RunRunAreaID equals ra.ID
            select new RunAreaViewModel
            {
                RunName = r.RunName,
                RunAreaName = ra.RunAreaName

            }).ToList();

    XmlSerializer sSubmit = new XmlSerializer(typeof(RunAreaViewModel));
    StringWriter sw = new StringWriter();
    XmlWriter xw = XmlWriter.Create(sw);
    sSubmit.Serialize(xw, theRuns);
    var xml = sw.ToString();

    return Content(xml, "application/xml");

    /*return View(theRuns);*/
}

And this is one node I would like to generate for now,

<Run>
    <RunName>Wishing Well</RunName>
    <RunAreaName>The Maze</RunAreaName>
</Run>

I have no problem producing a Razor View with the code but I can't get it to produce an XML feed. I get an error:

Unable to cast object of type 'System.Collections.Generic.List`1[namespace.Models.RunAreaViewModel]' to type namespace.Models.RunAreaViewModel'.

Any ideas,

Upvotes: 0

Views: 423

Answers (1)

Mike Hixson
Mike Hixson

Reputation: 5189

When you construct your serializer, you are specifying typeof(RunAreaViewModel), but what you are actually trying to serialize is typeof(List<RunAreaViewModel>). Try creating your serializer like this:

XmlSerializer sSubmit = new XmlSerializer(typeof(List<RunAreaViewModel>));

Upvotes: 1

Related Questions