Bojje Bojje - 9 days ago 5
C# Question

How would one go about to create or display an image from MVC Controller?

I'm new to MVC and trying to figure out it works. I'm just experimenting with simple projects, and there are somethings that are unclear.

Let's say I want to load an image depending on value (true or false from a checkbutton) from my controller. I have no problem with recieving the value from my view but how would I go in generating this html element?

A few ideas that comes to mind is.


  • Use
    IsVisible=false
    attribute on already rendered image element and then just change that attribute with CSS

  • Use
    ViewBag
    to send data between
    View
    and
    Controller

  • Use
    Html.Helper
    to create a "personalized" element.



What is the way to go in creating element from a Controller and pass it to a View regarding "Best-pratice" ?

Answer

Build it like this:

View model/model

public class viewModel
{
    public string imgSrc {get; set;}
}

Controller

public class myController : Controller
{
    public ActionResult myAction()
    {
       bool switch;
       viewModel vm = new viewModel();
       if (switch)
            vm.Src = "something.jpg";
       else
            vm.Src = "somthingelse.jpg";
       return View(vm);
    }

}

Razor

@model viewMoel

<img src="@Model.Src"/>

MVC is based on seperation of concerns. Read about the design pattern. People often think MVC is a technology, it's not, it's a pattern.

As such it should be used correctly with the correct parts doing what they are designed to do. So just because you can do something, doesn't mean you should. In MVC the views job (concern) is rendering the content. The controller should have no knowledge of this content. It's job is routing and generating of the Model. So all you HTML should be in the view (full stop)

Comments