Christopher Hunt Christopher Hunt - 5 months ago 35
JSON Question

MVC Return Content vs Return View

How can I encapsulate the following code and incorporate it into my view?

public ActionResult Index()
{
string restURL = "http://loripsum.net/api/3/medium/";
using (var client = new WebClient())
{
var data = client.DownloadString(restURL);
return Content(data, "application/json");
}

}


As you can see, I'm not accessing my view page at all, and I'm not sure how to insert this code into the view I have. Can I turn this into a function and then call it with return View(foo)?

Thanks! Sorry, It's been years since I've used mvc

Answer

So if I get your meaning, you're wanting to embed "data" within a view you already have - so depending on what "data" is, you should create a ViewModel (just a standard C# class) with a property in it - lets assume data is a string since you're retrieving it as a string. Set the property's value to data, then return your View from this method, and pass in your new ViewModel.

public class MyViewModel
{
    public string LoremContent { get; set; }
}

...

public ActionResult Index()
{
    string restURL = "http://loripsum.net/api/3/medium/";
    using (var client = new WebClient())
    {
        var data = client.DownloadString(restURL);
        MyViewModel model = new MyViewModel() { LoremContent = data };
        return View(model);
    }
}

Then in your view you can refer to @Model.LoremContent - if it's HTML you can just use @Html.Raw(Model.LoremContent) to render it. Be sure to validate the content if you're going to do this, otherwise you're making yourself vulnerable to a script attack.

Comments