Reputation: 147
I am currently working on the MVC 5 based project. Now for retrieving the few text content from Database, I have made the API call to get the text to be used in the View. Here my View is a basically simple form where few of the text comes from Database.
Now while loading the Page, I found that Image is not loaded initially while the page is being loaded. I am bringing the Image path from the Database using API call where I have stored the particular list of data from Cache.
Now I am not sure about where should I put a call to API. I am created the common function to make the call to API to retrieve the Data.
I have to option to choose from
1) Place the Call directly inside the Src attribute inside my image tag
<img src="@myfunctioncall" style="max-height:50px;" />
2) On the top of the View, Inside the C# block, I should declare the variable and then make a call to API and then use that variable inside the Src attribute inside my image tag.
On top of the View
@{
string myVal = myfunctioncall;
}
then use myVal inside my img tag
.........Code......
<img src="@myVal" style="max-height:50px;" />
.........Code......
I am not sure about how the page is rendered and which is the best approach to get the job done.
Upvotes: 0
Views: 120
Reputation: 3890
The right approach is:
1) Build a model:
public class MyModel
{
public string ImagePath {get;set;}
//other properties
}
2) Controller:
public class MyController:Controller
{
public ActionResult Index()
{
MyModel model = new MyModel();
model.ImagePath = //here get it from service
return View(model);
}
}
3) View:
<img src="@Model.ImagePath" style="max-height:50px;" />
In the first line of the View you need to add:
@model MyModel
Another (not suggested) option is:
ViewBag
that is not strongly typed, as it's type is dynamic
, which means errors in typos etc won't get caught in the build process, but in the runtime.
Controller:
public class MyController:Controller
{
public ActionResult Index()
{
ViewBag.ImagePath = //your service call
return View();
}
}
View:
<img src="@ViewBag.ImagePath" style="max-height:50px;" />
The idea to put a service call in the View
is the violation of MVC
pattern, where View
supposed to be as stupid as possible.
It's just representation layer.
Upvotes: 1
Reputation: 398
In the controller, you have to write the code to retrieve data from the database and then create a view Bag as ViewBag.Path= imagePath;
where imagePath
is the c# string variable in which it contains the path value retrieved from the database.Then in the View you can use the ViewBag as <img src="@ViewBag.Path" style="max-height:50px;" />
Upvotes: 2
Reputation: 63
The best way is to make all operation in your controller et make an object you pass as Model to your view.
In your view, your can use your Model for fill your field.
Upvotes: 0