How To Display Byte[] As Picture In MVC4 - asp.net-mvc

I have a model that contains a Byte[] type property .I want to display this property in MVC View in html tag.What approach I can use to display this image?

This is what I need to do in my project:
For each instance of my object collection I put below tag in Razor View
<img src="#Url.Action("GetPhoto", new { photoId = Model.PhotoId })" />
And then in Controller I added a Action:
public ActionResult GetPhoto(int photoId)
{
byte[] photo = GetPhotoFromDb(photoId);
return File(photo, "image/jpeg"); }

Create an action on your controller to return the file response:
public class MyController : Controller
{
public ActionResult ViewFile()
{
byte[] bytes;
string mime;
return File(bytes, mime);
}
}
You can then display the image like so:
<img src="/mycontroller/viewfile" />
EDIT:
A detailed example:
public class Photo
{
public int ID {get;set;}
public string Title {get;set;}
}
public class PhotoController : Controller
{
public ActionResult Index()
{
return View(new List<Photo> { new Photo { ID = 1, Title = "first" }, new Photo { ID = 2, Title = "second" }});
}
public ActionResult Photo(int ID)
{
return File(GetPhotoBytes(ID), "image/jpg");
}
}
View:
#model IEnumerable<Photo>
#foreach (var photo in Model)
{
<img src="#Url.Action("photo", "photo", new { ID = photo.ID })" title="#photo.Title" />
}

Related

I want to show selected value of dropdown list

Selected value is not coming when I am trying to check, drop down list is showing all the names, but when I am trying to show the selected value of the dropdownlist in the controller, option is not coming.
Controller:
public ActionResult Index1()
{
Class1 cs1 = new Class1();
return View(cs1);
}
[HttpPost]
public ActionResult Index1(Class1 cs)
{
var selecteditem = cs.psudetail.Find(p => p.Section_PSU == cs.psudetail.ToString());
if (selecteditem != null)
{
}
}
Model class:
namespace WebApplication1.Models
{
public class Class1
{
public List<PSUMaster> psudetail
{
get
{
PSUEntities pe = new PSUEntities();
return pe.PSUMasters.ToList();
}
}
}
}
And the View with Model:
#model WebApplication1.Models.Class1
#{
ViewBag.Title = "Index1";
}
<br />
#Html.DropDownListFor(m => m.psudetail, new SelectList(Model.psudetail, "S_no", "Section_PSU"), "--Select PSU--")
You need to have a property that can "store" the selection you make in the list. Extend the view model (Class1) to include a property SelectedPSU. I guess that S_no in the PSUMaster is the ID, and of type integer. Otherwise adjust the code accordingly!
I have also changed the list to be just a list, and then the controller can worry about populating it. This pattern fits MVC better (keep the model simple).
Updated class:
namespace WebApplication1.Models
{
public class PsuViewModel
{
public int SelectedPSU { get; set; }
public List<PSUMaster> PSU { get; set; }
}
}
Next, the controller has to be updated to pass the list to the view model in the GET Index method:
public ActionResult Index1()
{
var pe = new PSUEntities();
return View(new PsuViewModel {
PSU = pe.PSUMasters.ToList()
});
}
Now we can use the SelectedPSU property in our view:
#model WebApplication1.Models.Class1
#{
ViewBag.Title = "Index1";
}
<br />
#Html.DropDownListFor(m => m.SelectedPSU, new SelectList(Model.PSU, "S_no", "Section_PSU"), "--Select PSU--")
...and we can get the ID in the controller:
[HttpPost]
public ActionResult Index1(PsuViewModel model)
{
var pe = new PSUEntities();
var selectedPsu = pe.PSUMasters.FirstOrDefault(p => p.S_no == model.SelectedPSU);
if (selectedPsu != null) {
// ...
}
}

MVC Error using Lists and Model

I am very new to this and am doing a little project to get to know how it all works.
So I'm looking to create a header image area on each page by placing the code in the "_Layout.cshtml" file and attempting to control what image displays according to "ViewBag.Title".
I have broken the code up into the pages, followed by a pic. of the error. I just can't work out what the problem is.
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebSite_Project_1.Controllers
{
public partial class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
[ActionName("Funny-Bones")]
public ActionResult FunnyBones()
{
ViewBag.Message = "This is funny bones.";
return View();
}
public class Headers
{
public string HeaderName { get; set; }
public string PageName { get; set; }
public int HeaderWidth { get; set; }
public int HeaderHeight { get; set; }
public string HeaderType { get; set; }
}
public ActionResult HeaderImages()
{
var model = new List<Headers>();
model.Add(new Headers { HeaderName = "home", PageName = "Home Page", HeaderWidth = 2200, HeaderHeight = 1172, HeaderType = ".png" });
model.Add(new Headers { HeaderName = "about", PageName = "About", HeaderWidth = 2200, HeaderHeight = 1172, HeaderType = ".png" });
model.Add(new Headers { HeaderName = "contact", PageName = "Contact", HeaderWidth = 2200, HeaderHeight = 1172, HeaderType = ".png" });
model.Add(new Headers { HeaderName = "funnybones", PageName = "Funny Bones", HeaderWidth = 2200, HeaderHeight = 1172, HeaderType = ".png" });
return View(model);
}
}
}
_Layout.cshtml
#model IEnumerable<WebSite_Project_1.Controllers.HomeController.Headers>
<div class="headersImage">
#foreach (var item in Model)
{
if (#item.PageName == #ViewBag.Title)
{
<img src="~/Content/Images/#item.HeaderName+#item.HeaderType" title="#item.HeaderName" />
}
}
</div>
#RenderBody()
The problem starts when I try and publish it and then i get this error pointing to Model in the "foreach" loop.
I'm not a 100% sure the loop is right, but haven't been able to get that far yet.
Link to MVC error
You should never specify a model for a layout. The model passed in will always be the one for the view, which almost invariably, will not be the same one the layout is wanting.
For things like this, you should use child actions. Essentially, just take your existing HeaderImages action, add the [ChildActionOnly] attribute (which prevents it from being routed to directly), and change the return to:
return PartialView("_HeaderImages", model);
You can call the view whatever you want, but essentially it would just have the following:
#model IEnumerable<WebSite_Project_1.Controllers.HomeController.Headers>
<div class="headersImage">
#foreach (var item in Model)
{
if (#item.PageName == #ViewBag.Title)
{
<img src="~/Content/Images/#item.HeaderName+#item.HeaderType" title="#item.HeaderName" />
}
}
</div>
Finally, in your layout, remove the model definition line and replace the header image code currently there with:
#Html.Action("HeaderImages", "Home")
EDIT
Sorry, I missed one thing. The child action will render in a separate context from the main view/layout (that's sort of the point). However, that means it has its own ViewBag, so you can't access the ViewBag from the main action directly. Instead, you'll need to pass it in as a route value:
#Html.Action("HeaderImages", "Home", new { title = ViewBag.Title })
Then, modify your child action to accept this param, and set its ViewBag:
[ChildActionOnly]
public ActionResult HeaderImages(string title)
{
...
ViewBag.Title = title;
return PartialView("_HeaderImages", model);
}

System.NullReferenceException when trying to iterate list in view

Im a bit new at mvc, and i dont find out what am i miss. When i launch the login, in the view at foreach (var item in Model) <- the Model gets null, and stops with a System.NullReferenceException. A dont really have a clue why, and i hope somebody can give some advice what's wrong with the following code or where to start looking for the error.
The model:
public class LoginModels
{
public string UserLogin { get; set; }
public string Address { get; set; }
public string Password { get; set; }
public List<string> emailSubject { get; set; }
}
The controller:
public ActionResult Login(string address, string password, LoginModels model)
{
using (Imap imap = new Imap())
{
try
{
imap.ConnectSSL("imap.gmail.com");
imap.Login(address, password);
imap.SelectInbox();
List<long> uids = imap.Search(Flag.All);
model.emailSubject = new List<string>();
foreach (long uid in uids)
{
var eml = imap.GetMessageByUID(uid);
IMail email = new MailBuilder().CreateFromEml(eml);
model.emailSubject.Add(email.Subject);
}
Session["user"] = new LoginModels() { UserLogin = address, Address = address };
return RedirectToAction("Index", "Home", model.emailSubject);
}
catch (Exception e)
{
ViewBag.exceptionMessage = e;
return View("LoginFailed");
}
}
The view:
#using TheOnlineArchivator.Models;
#model List<TheOnlineArchivator.Models.LoginModels>
#{
ViewBag.Title = "Home";
}
#{
var user = Session["user"] as LoginModels;
if (user != null)
{
<h2>You are logged on as #user.Address</h2>
<table>
#foreach (var item in Model)
{
foreach (var elem in item.emailSubject)
{
<tr>
<td>#elem</td>
</tr>
}
}
</table>
}
}
It looks like you forgot to pass an instance of List<TheOnlineArchivator.Models.LoginModels> to the view when you rendered this view inside your controller action. What you have shown so far is your Login controller action but you didn't show us your Home/Index action. Inside this action you should make sure that you are passing a non-null model to the view:
public class HomeController : Controller
{
public ActionResult Index()
{
List<LoginModels> model = ... go get your model from somewhere and make sure it is not null
return View(model);
}
}

Getting Selected Values from Multiple Dropdowns in MVC web application

I am trying to build a web application having multiple drop downs. I have used enums in my model to populate these drop down and there is a single from submit button in my view. I am trying to figure out how could I get all the selected Index from these drop down with 1 button click.
My Controller looks something like this:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new DropDownModel();
return View(model);
}
[HttpPost]
public ActionResult Index(DropDownModel model)
{
// Get the selected value
int id = model.SelectedId;
return View();
}
public ActionResult About()
{
return View();
}
}
DropDown in my view:
#Html.DropDownListFor(x => x.SelectedId, Enum.GetNames(typeof(BTSWeb.Models.BillTemplate)).Select(e => new SelectListItem { Text = e }),"--BillTemplate--",new { style = "width:108px;font-size:90%;border-radius: 6.5px 6.5px 6.5px 6.5px" })
<span style="margin-left:1px"></span>
#Html.DropDownListFor(x => x.SelectedId, Enum.GetNames(typeof(BTSWeb.Models.ReadType)).Select(e => new SelectListItem { Text = e }),"--Read Type--",new { style = "width:70px;font-size:90%;border-radius: 6.5px 6.5px 6.5px 6.5px" })
<input type="submit" value="Submit" hidden="hidden"/>
and My Model:
namespace BTSWeb.Models
{
public enum States { ANY, FL, TX, GA, NE };
public enum PaymentType { ANY, Email, Paper, No };
public class DropDownModel
{
public int SelectedId { get; set; }
}
}
The problem is you are using DropDownModel as your view model. You will only ever be able to populate on selectedID using this. What you need to do is somehting like
public class ViewModel
{
public int SelectedStateId { get; set; }
public int SelecPaymentTypeId { get; set; }
}
then in your controller you would pass in
var viewModel = new ViewModel()
return View(ViewModel);
and on your view you would have
#Html.DropDownListFor(x => x.SelectedStateId, Enum.GetNames(typeof(BTSWeb.Models.BillTemplate)).Select(e => new SelectListItem { Text = e }),"--BillTemplate--",new { style = "width:108px;font-size:90%;border-radius: 6.5px 6.5px 6.5px 6.5px" })
<span style="margin-left:1px"></span>
#Html.DropDownListFor(x => x.SelecPaymentTypeId , Enum.GetNames(typeof(BTSWeb.Models.ReadType)).Select(e => new SelectListItem { Text = e }),"--Read Type--",new { style = "width:70px;font-size:90%;border-radius: 6.5px 6.5px 6.5px 6.5px" })
and finally on your controller post method you would have
[HttpPost]
public ActionResult Index(ViewModelmodel)
{
// Get the selected value
int id = model.SelectedStateId;
int id2 = model.SelecPaymentTypeId;
return View();
}

How can use MVC DropDownlist

I have a problem with DropDownlist in MVC
I use ModelView in my application and this is my code
namespace MedicallexiconProject.ViewModel
{
public class WordViewModel
{
private readonly ICategoryService _categoryService;
public WordViewModel(ICategoryService categoryService)
{
_categoryService = categoryService;
var selectList = _categoryService.GetAllCategorysSelectList().
Select(x => new SelectListItem
{
Text = x.Name,
Value = x.ID.ToString()
}).ToList();
Categories = selectList;
}
public WordViewModel()
{
}
public string Name { get; set; }
private IList<SelectListItem> _categories;
public IList<SelectListItem> Categories
{
get
{
if (_categories == null)
{
_categories = new List<SelectListItem>();
}
return (_categories);
}
set { _categories = value; }
}
}
}
and this is my controller
[HttpGet]
public ActionResult Create()
{
var wordViewModel = new WordViewModel(_categoryService);
ViewBag.CategoryID = wordViewModel.Categories;
return View();
}
[HttpPost]
public ActionResult Create(WordViewModel wordViewModel)
{
Mapper.CreateMap<WordViewModel, Word>();
var word = new Word();
Mapper.Map(wordViewModel, word);
if (ModelState.IsValid)
{
_wordService.AddNewWord(word);
_uow.SaveChanges();
return RedirectToAction("Index");
}
return View(wordViewModel);
}
Now how can I insert dropdownlist in my View?
As AlfalfaStrange mentioned, you should not add logic in your ViewModel. That makes it ugly ! Keep your ViewModel simple POCO.
Add one more property in your ViewModel called "SelectedCategoryID" like this
public class WordViewModel
{
public int SelectedCategoryID { set;get;}
public IList<SelectListItem> Categories { set;get;}
public string Name { set;get;}
}
Initialize your Items (Categories) of your ViewModel in your GET method. Here i am calling a method called GetCategories which returns a list of categories.I can simply call the method wherever i want.
public ActionResult Create()
{
var model=new WordViewModel();
model.Categories=YourService.GetCategories();
return View(model);
}
In your strongly typed Create view , use this
#model WordViewModel
using(#Html.BeginForm())
{
#Html.DropDownFor(x=>x.SelectedCategoryID,
new SelectList(Model.Categories,"Value","Text"),"Select Category")
<input type="submit" value="Save" />
}
In your HttpPost action method , you can check for wordViewModel.SelectedCategoryID for the selected value.
[HttpPost]
public ActionResult Create(WordViewModel wordViewModel)
{
if(ModelState.IsValid)
{
//Checck for wordViewModel.SelectedCategoryID here now
}
//some validation failed. Let's reload the category data again.
wordViewModel.Categories=YourService.GetCategories();
return View(wordViewModel);
}
It's absolutely fine to include code that loads a dropdown list in your view model. A select list and a drop down are both "view" items.... they are not related to business logic and your controller and model need not know anything about SelectLists or SelectListItems or DropDownList, etc.

Resources