How to list checked enum values only? - checkbox

I’m learning Blazor and was trying to put/save in a list some enum elements, only the ones that are checked. I have read loads of hints on stackoverflow and other web sites but am still unable to achieve that, I know something is missing but I’m blind for now
Let’s say I have an enum in a separate class calle Enums:
public enum Browsers
{
Chrome,
Edge,
Firefox,
Opera,
Safari,
Vivaldi
}
Here is the html part:
#page "/Sub2"
#using TestPatternBuilder.Data
<div class="col">
<div>Browsers:</div>
#foreach (var browser in Enum.GetValues<Browsers>())
{
<input class="form-check-input mx-0" type="checkbox" id="browsers" value="#browser" />
<label class="ms-1" for="browsers">#browser</label><br />
}
<button class="btn btn-secondary my-3" #onclick="AddBrowsers">Add Browsers</button>
<ul class="mt-2">
#foreach (var br in selectedBrowsers)
{
<li>#br.BrowserName</li>
}
</ul>
</div>
And the code part:
#code{
List<TestBrowser> selectedBrowsers = new List<TestBrowser>();
private void AddBrowsers()
{
foreach (Browsers item in Enum.GetValues(typeof(Browsers)))
{
selectedBrowsers.Add(new TestBrowser { BrowserName = item, isChecked = true });
}
}
}
I seem to have it all wrong, tried to bind without success, no idea where the isChecked state is missing...
[enter image description here](https://i.stack.imgur.com/R7y6a.png)

To achive this you'll need some sort of object to hold both your checked state as well as the enum value. For example:
public class SelectableBrowsers
{
public bool IsChecked { get; set; }
public Browsers Browser { get; set; }
}
Then you can generate a List of all enum values like this:
private List<SelectableBrowsers> _browsers = new List<SelectableBrowsers>();
protected override void OnInitialized()
{
foreach (var browser in Enum.GetValues<Browsers>())
{
_browsers.Add(new SelectableBrowsers
{
Browser = browser
});
}
}
Now you can output the browsers based on your generated list like this:
#foreach (var browser in _browsers)
{
<input #bind="browser.IsChecked" class="form-check-input mx-0" type="checkbox" id="browsers" />
<label class="ms-1" for="browsers">#browser.Browser</label><br />
}
Finally in your AddBrowsers you can loop every selected element like this:
private void AddBrowsers()
{
foreach (selectedBrowsers browser in _browsers.Where(x => x.IsChecked))
{
selectedBrowsers.Add(new TestBrowser { BrowserName = item.Browser, isChecked = true });
}
}
Hope this helps :)

An interesting alternative using Enum Flags:
#page "/"
<PageTitle>Index</PageTitle>
<h1>Hello, world!</h1>
Welcome to your new app.
<div>
#foreach (var browser in Enum.GetValues<Browsers>())
{
<div>
<input class="form-check-input mx-0" type="checkbox" id="browsers" value="#(isSelected(browser))" #onchange="() => AddToList(browser)" />
<label class="ms-1" for="browsers">#browser</label>
</div>
}
</div>
<div class="alert alert-info mt-2">
#foreach (var browser in Enum.GetValues<Browsers>())
{
#if (browser == (selectedBrowsers & browser))
{
<div>
#browser
</div>
}
}
</div>
#code {
private Browsers selectedBrowsers;
private bool isSelected(Browsers browser)
=> (selectedBrowsers & browser) == browser;
private Task AddToList(Browsers browser)
{
if ((selectedBrowsers & browser) == browser)
selectedBrowsers &= ~browser;
else
selectedBrowsers = selectedBrowsers | browser;
return Task.CompletedTask;
}
public enum Browsers
{
Chrome = 1,
Edge = 2,
Firefox = 4,
Opera = 8,
Safari = 16,
Vivaldi = 32
}
}

Related

Episerver create page programmatically

I am using this code
var parent = ContentReference.StartPage;
IContentRepository contentRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
PageData myPage = contentRepository.GetDefault<LoginPage>(parent);
myPage.PageName = "My new page";
var page = contentRepository.GetChildren<LoginPage>(parent).FirstOrDefault(name => name.Name == myPage.Name);
if (page == null)
contentRepository.Save(myPage, EPiServer.DataAccess.SaveAction.Publish);
to create a page programatically. The thing is I am not sure where to put this code?
I don't want to show LoginPage which is page type to show in the list in the admin/edit panel as I want to create only one page under that page type. Maybe there is another way where I can just create a stand alone page and don't have to create the page type or maybe use an already made page type.
This is the code for my page type
[ContentType(DisplayName = "Custom Login Page", GUID = "c0d358c3-4789-4e53-bef3-6ce20efecaeb", Description = "")]
public class LoginPage : StandardPage
{
/*
[CultureSpecific]
[Display(
Name = "Main body",
Description = "The main body will be shown in the main content area of the page, using the XHTML-editor you can insert for example text, images and tables.",
GroupName = SystemTabNames.Content,
Order = 1)]
public virtual XhtmlString MainBody { get; set; }
*/
}
Then I am creating a model like this
public class LoginModel : PageViewModel<LoginPage>
{
public LoginFormPostbackData LoginPostbackData { get; set; } = new LoginFormPostbackData();
public LoginModel(LoginPage currentPage)
: base(currentPage)
{
}
public string Message { get; set; }
}
public class LoginFormPostbackData
{
public string Username { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }
public string ReturnUrl { get; set; }
}
And my controller looks like this
public ActionResult Index(LoginPage currentPage, [FromUri]string ReturnUrl)
{
var model = new LoginModel(currentPage);
model.LoginPostbackData.ReturnUrl = ReturnUrl;
return View(model);
}
Do you think there is another way to do it? I will also show my login view
#using EPiServer.Globalization
#model LoginModel
<h1 #Html.EditAttributes(x =>
x.CurrentPage.PageName)>#Model.CurrentPage.PageName</h1>
<p class="introduction" #Html.EditAttributes(x =>
x.CurrentPage.MetaDescription)>#Model.CurrentPage.MetaDescription</p>
<div class="row">
<div class="span8 clearfix" #Html.EditAttributes(x =>
x.CurrentPage.MainBody)>
#Html.DisplayFor(m => m.CurrentPage.MainBody)
</div>
#if (!User.Identity.IsAuthenticated &&
!User.IsInRole("rystadEnergyCustomer"))
{
<div class="row">
#using (Html.BeginForm("Post", null, new { language = ContentLanguage.PreferredCulture.Name }))
{
<div class="logo"></div>
#Html.AntiForgeryToken()
<h2 class="form-signin-heading">Log in</h2>
#Html.LabelFor(m => m.LoginPostbackData.Username, new { #class = "sr-only" })
#Html.TextBoxFor(m => m.LoginPostbackData.Username, new { #class = "form-control", autofocus = "autofocus" })
#Html.LabelFor(m => m.LoginPostbackData.Password, new { #class = "sr-only" })
#Html.PasswordFor(m => m.LoginPostbackData.Password, new { #class = "form-control" })
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.LoginPostbackData.RememberMe)
#Html.DisplayNameFor(m => m.LoginPostbackData.RememberMe)
</label>
</div>
#Html.HiddenFor(m => m.LoginPostbackData.ReturnUrl, "/login-customers")
<input type="submit" value="Log in" class="btn btn-lg btn-primary btn-block" />
}
#Html.DisplayFor(m => m.Message)
</div>
}
else
{
<span>Welcome #User.Identity.Name</span>
#Html.ActionLink("Logout", "Logout", "LoginPage", null, null);
}
I think you're misunderstanding some of the Episerver concepts.
If you don't want it to be a page in Episerver, you shouldn't use PageController, page types, or templates. Instead, just use a standard controller and view to create your login page.
Otherwise, you do have to create a page of type LoginPage, which will be visible in the page tree. No need to create it programmatically, you can just add the page manually and then hide the LoginPage type from edit mode to avoid editors creating additional login pages.

How to send list inside model - AngularJS

i have a problem with my model.
I need send a list of another object to my controller, but i dont know how to create this object using AngularJS.
I have three input field, homePhone, cellphone and contact, all fields are about phone, and my ClientModel has a list of phones. What i want to do, is get this three fields and include in a list inside client model.
**MVC Model "Client"**
public int Id { get; set; }
public string Name { get; set; }
public string Email{ get; set; }
public IEnumerable<Phone> Phones { get; set; }
**MVC Model "Phone"**
public int PhoneId { get; set; }
public int ClientId { get; set; }
public int PhoneType { get; set; }
public string Number { get; set; }
View
<div class="form-group col-lg-4">
<label>Home Phone</label>
<input class="form-control" ng-model="?">
</div>
<div class="form-group col-lg-4">
<label>Cellphone</label>
<input class="form-control" ng-model="?">
</div>
<div class="form-group col-lg-4">
<label>Contact Phone</label>
<input class="form-control" ng-model="?">
</div>
<button class="btn btn-primary" style="float: right" ng-click="saveClient(client)">Confirmar</button>
Controller JS
$scope.saveClient = function(client) {
clientesAPI.saveCliente(client).success(function() {
alert('OK');
}).error(function () {
alert('Error');
});`enter code here`
}
What you could do is create actual Constructor functions in JS and consistently model you current Server Side MVC Model.
So is would look something like this ...
angular.module('app', [])
.factory('Client', function() {
return Client;
function Client() {
this.id = 0;
this.name = '';
this.email = '';
this.phones = [];
}
Client.prototype.init = function(client) {
this.id = client.id;
this.name = client.name;
this.email = client.email;
this.phones = [];
}
})
.factory('Phone', function() {
return Phone;
function Phone() {
this.phoneId = 0;
this.clientId = 0;
this.phoneType = 'Default Phone Type';
this.number = 0;
}
Phone.prototype.init = function(phone) {
this.phoneId = phone.phoneId;
this.clientId = phone.clientId;
this.phoneType = phone.phoneType;
this.number = phone.number;
}
})
.factory('clientService', function($http, $log, Client, Phone) {
var service = {
getClient: getClient,
saveClient: saveClient
};
return service;
//////////////////////////
function getClient() {
return $http.get('clientApi')
.then(success)
.catch(error)
// This is where defining actual JS Quote unQuote Classes comes in handy
function success(response) {
var clients = response.data;
angular.forEach(clients, function(client) {
client = new Client().init(client);
angular.forEach(client.phones, function(phone) {
phone = new Phone().init(phone);
})
})
return clients;
}
function error(response) {
$log.error('Error getting Clients: ' + response.data);
}
}
function saveClient(client) {
return $http.post('clientApi', client)
.then(success)
.catch(error)
// This is where defining actual JS Quote unQuote Classes comes in handy
function success(response) {
$log('Saved Client Successfully');
}
function error(response) {
$log.error('Error saving Client: ' + response.data);
}
}
})
// I would use Controller As Syntax normally
.controller('clientController', function($scope, clientService, Client, Phone) {
$scope.client = new Client();
$scope.client.phones.push(new Phone());
$scope.savedClient;
$scope.saveClient = function() {
$scope.savedClient = $scope.client;
alert('Yeah we saved some data!!');
//Unconmment this to access the real service, Nowhere to call here :-)
//clientService.saveClient($scope.client);
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="clientController">
<!-- Use ngRepeat to simplify things a bit -->
<div class="form-group col-lg-4" ng-repeat="phone in client.phones track by phone.phoneId">
<label>{{phone.phoneType}}</label>
<input class="form-control" ng-model="phone.number">
</div>
<!-- You will already have access to the updated model in you controller -->
<button class="btn btn-primary" style="float: right" ng-click="saveClient()">Confirmation</button>
<!--Display Saved Data-->
<pre>{{savedClient | json}}</pre>
</div>
</div>
I like the idea of this approach for a couple of reasons.
You can new up a Client or a Phone in you controller and know for a fact that or expected model properties are there when Angular tries to render them. (This avoids the annoying client.phones.phoneId is not defined errors)
Your model definition is now in one spot on the JS side of the house. Even though this looks like duplication ... well it is, but you will have to define this somewhere to send it back to the server anyways. So I prefer to do it in one reusable spot.
You get and Arrays of Client and Phone when you are outputting the model properties to the Console. This just make me feel good :-)
This was a bit of an overkill for your question, but I like the clean feel of this approach to Front End Modeling.
You can create a new object for your model and add the phones property there.
View
<div class="form-group col-lg-4">
<label>Home Phone</label>
<input class="form-control" ng-model="homePhone">
</div>
<div class="form-group col-lg-4">
<label>Cellphone</label>
<input class="form-control" ng-model="cellPhone">
</div>
<div class="form-group col-lg-4">
<label>Contact Phone</label>
<input class="form-control" ng-model="contactPhone">
</div>
<button class="btn btn-primary" style="float: right" ng-click="saveClient()">Confirmar</button>
Controller
$scope.saveClient = function() {
var phones = [
{ClientId: $scope.client.Id, PhoneType: 1, Number: $scope.homePhone},
{ClientId: $scope.client.Id, PhoneType: 2, Number: $scope.cellPhone},
{ClientId: $scope.client.Id, PhoneType: 3, Number: $scope.contactPhone}
]; // Not sure about the PhoneTypes. There are multiple ways to implement this, I'll leave it up to you.
var data = {
Id: $scope.client.Id,
Name: $scope.client.Name,
Email: $scope.client.Email,
Phones: phones
};
clientesAPI.saveCliente(data).success(function() {
alert('OK');
}).error(function () {
alert('Error');
});
};
first you need to define ng-model for your view, suppose -
<input class="form-control" ng-model="hPhone">
<input class="form-control" ng-model="cellPhone">
<input class="form-control" ng-model="contactPhone">
Now you can make a json object and post that, then on server side you can access all the phones by for-each loop -inside your controller -
var vm = this;
var phnList = {
hphone: vm.hphone,
cellPhone: vm.cellPhone,
contactPhn: vm.contactPhone
};
Now u can post using $http service
$(http).({
url : "urULR",
data : phnList,
method :"post"
}).then(fuction(response) {
vm.message = "save success";
});

How to insert an image into sql server database?

As said, i'm trying to insert an image in a table, where the type of the field is Varbinary.
What i've done so far :
I've a form with many fields:
#using (Html.BeginForm("InsertProduct", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>PRODUCT</legend>
<div class="editor-label">
#Html.LabelFor(model => model.PRODUCT_ID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PRODUCT_ID)
#Html.ValidationMessageFor(model => model.PRODUCT_ID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PRODUCT_NAME)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PRODUCT_NAME)
#Html.ValidationMessageFor(model => model.PRODUCT_NAME)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PRODUCT_IMAGE)
</div>
<div class="editor-field">
<input type="file" name="PRODUCT_IMAGE" id="PRODUCT_IMAGE" style="width: 100%;" />
</div>
<p>
<input type="submit" value="Create" class="btn btn-primary"/>
</p>
</fieldset>
}
And all these fields allow me to construct a PRODUCT object in my controller :
public ActionResult InsertProduct(PRODUCT ord)
{
MigrationEntities1 sent = new MigrationEntities1();
sent.PRODUCT.Add(ord);
sent.SaveChanges();
List<PRODUCT> Products = sent.PRODUCT.ToList();
return View("Products", Products);
}
But when i'm trying to upload the image (by clicking on Create button), i've the following :
entry is not a valid base64 string because it contains a character
that is not base 64
So first of all : is it the right way to deal with images and second, I think I need to do a pre-treatemant on my image to insert it : how to o that ?
Thanks !
Edit :
Thanks to answers received, seems to be good for insertion. But for displaying, I still have issues (only the "not found image" piture is displayed). I've try to do it two ways :
1.
<img src="LoadImage?id=#Model.product.PRODUCT_ID"/>
and in the controller
public Image LoadImage(int id)
{
String serviceAddress = ConfigurationManager.AppSettings["WCFADDRESS"];
DataServiceContext context = new DataServiceContext(new Uri(serviceAddress));
PRODUCT product = context.Execute<PRODUCT>(new Uri(serviceAddress + "prod_id?prod_id=" + id)).ToList().FirstOrDefault();
MemoryStream ms = new MemoryStream(product.PRODUCT_IMAGE);
Image img = Image.FromStream(ms);
return img;
}
And 2. :
#{
if (Model.product.PRODUCT_IMAGE != null)
{
WebImage wi = new WebImage(Model.product.PRODUCT_IMAGE);
wi.Resize(700, 700,true, true);
wi.Write();
}
}
But none of them are working. What am I doing wrong ?
1) Change your database table to have these columns:
1: ProductImage - varbinary(MAX)
2: ImageMimeType - varchar(50)
2) Change your action method like this:
public ActionResult InsertProduct(PRODUCT ord,
HttpPostedFileBase PRODUCT_IMAGE)
{
if (ModelState.IsValid)
{
MigrationEntities1 sent = new MigrationEntities1();
if (image != null)
{
ord.ProductImage= new byte[PRODUCT_IMAGE.ContentLength];
ord.ImageMimeType = PRODUCT_IMAGE.ContentType;
PRODUCT_IMAGE.InputStream.Read(ord.ProductImage, 0,
PRODUCT_IMAGE.ContentLength);
}
else
{
// Set the default image:
Image img = Image.FromFile(
Server.MapPath(Url.Content("~/Images/Icons/nopic.png")));
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Png); // change to other format
ms.Seek(0, SeekOrigin.Begin);
ord.ProductImage= new byte[ms.Length];
ord.ImageMimeType= "image/png";
ms.Read(ord.Pic, 0, (int)ms.Length);
}
try
{
sent.PRODUCT.Add(ord);
sent.SaveChanges();
ViewBag.HasError = "0";
ViewBag.DialogTitle = "Insert successful";
ViewBag.DialogText = "...";
}
catch
{
ViewBag.HasError = "1";
ViewBag.DialogTitle = "Server Error!";
ViewBag.DialogText = "...";
}
List<PRODUCT> Products = sent.PRODUCT.ToList();
return View("Products", Products);
}
return View(ord);
}
This action method is just for create. you need some works for edit and index too. If you have problem to doing them, tell me to add codes of them to the answer.
Update: How to show images:
One way to show stored images is as the following:
1) Add this action method to your controller:
[AllowAnonymous]
public FileContentResult GetProductPic(int id)
{
PRODUCT p = db.PRODUCTS.FirstOrDefault(n => n.ID == id);
if (p != null)
{
return File(p.ProductImage, p.ImageMimeType);
}
else
{
return null;
}
}
2) Add a <img> tag in the #foreach(...) structure of your view (or wherever you want) like this:
<img width="100" height="100" src="#Url.Action("GetProductPic", "Products", routeValues: new { id = item.ID })" />
Change the Image type on the sql sever to Byte[] and use something like this. This is how I have stored images in the past.
http://www.codeproject.com/Articles/15460/C-Image-to-Byte-Array-and-Byte-Array-to-Image-Conv
If not, you can always just store the image locally and pass the image location through a string into the SQL data base, this method works well and is quick to set up.
So, here are the modifications to do :
To insert data in the database :
[HttpPost]
public ActionResult InsertProduct(PRODUCT ord, HttpPostedFileBase image)
{
MigrationEntities1 sent = new MigrationEntities1();
if (image != null)
{
ord.PRODUCT_IMAGE = new byte[image.ContentLength];
image.InputStream.Read(ord.PRODUCT_IMAGE, 0, image.ContentLength);
}
sent.PRODUCT.Add(ord);
sent.SaveChanges();
List Products = sent.PRODUCT.ToList();
return View("Products", Products);
}
Note: this is the "light" way, for something that is more complete, have a look to Amin answer.
For displaying :
In the view
<img src="LoadImage?id=#Model.product.PRODUCT_ID"/>
And in the controller :
public FileContentResult LoadImage(int id)
{
String serviceAddress = ConfigurationManager.AppSettings["WCFADDRESS"];
DataServiceContext context = new DataServiceContext(new Uri(serviceAddress));
PRODUCT product = context.Execute<PRODUCT>(new Uri(serviceAddress + "prod_id?prod_id=" + id)).ToList().FirstOrDefault();
return new FileContentResult(product.PRODUCT_IMAGE, "image/jpeg");
}
And everything is ok now, thanks !

Having some problems saving/displaying an image in MVC 4

I have searched around for a while now with no joy. I am trying to save an image to my SQL db as a byte array, then I am trying to display it later. The display part is not working. I don't know if it's a problem with the save or the display. The save appears to be working ok, I can see 'Binary Data' in my SQL table. Any suggestions?
What's happening is that I get a broken image icon on my page. Even if I manually goto the URL e.g. .../Treatments/LoadImage/14 it's broken.
Model contains this in my table definition:
public byte[] Photo { get; set; }
Create View:
<div class="editor-label">
#Html.LabelFor(model => model.Photo)
</div>
<div class="editor-field">
<input type="file" name="photo" />
</div>
Create Controller:
[HttpPost]
public ActionResult Create([Bind(Exclude = "Photo")]Treatment treatment)
{
if (ModelState.IsValid)
{
treatment.Photo = GetByteArrayFromFile();
treatment.WebOrder = db.Treatments.Count();
db.Treatments.Add(treatment);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.TreatmentTypeId = new SelectList(db.TreatmentTypes, "Id", "Name", treatment.TreatmentTypeId);
return View(treatment);
}
private byte[] GetByteArrayFromFile() {
int fileLength = Request.Files["photo"].ContentLength;
byte[] byteArray = new byte[fileLength];
return byteArray;
}
Display View:
<div class="display-label">
#Html.DisplayNameFor(model => model.Photo)
</div>
<div class="display-field">
<img src="#Url.Action("LoadImage", new { Id = Model.Id })" />
</div>
LoadImage Controller:
public ActionResult LoadImage(int Id) {
byte[] bytes = db.Treatments.Find(Id).Photo;
return File(bytes, "image/jpeg");
}
I have added:
#using (Html.BeginForm("Create", "Treatments", FormMethod.Post, new { enctype = "multipart/form-data" })) {
// View Code Omitted
}
to my Create view.
Is there something elementary wrong with my code? Any suggestions? Thanks.
It was a problem with my GetByteArrayFromFile Method. My original method above returned an array of zeros only. Using this, I fixed my issue:
private byte[] GetByteArrayFromFile() {
WebImage image = WebImage.GetImageFromRequest();
byte[] byteArray = image.GetBytes();
return byteArray;
}

Image saved in database cannot be updated

I have been googling for a solution to my problem for two days without any luck. Can any stars in MVC3 .NET help?
I am trying to build an .NET MVC3 application to update images saved in an database.
Here is the action method
[HttpPost]
public ActionResult Edit(myImage img, HttpPostedFileBase imageFile)
{
//var img = (from imga in db.myImages
// where imga.imageID == id
// select imga).First();
if (ModelState.IsValid)
{
if (img != null)
{
img.imageType = imageFile.ContentType;
img.Data = new byte[imageFile.ContentLength];
imageFile.InputStream.Read(img.Data, 0, imageFile.ContentLength);
}
// save the product
UpdateModel(img);
db.SubmitChanges();
return RedirectToAction("Index");
}
else
{
// there is something wrong with the data values
return View(img);
}
}
Here is the view
#model JackLing.Models.myImage
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("Edit", "Image",FormMethod.Post, new { enctype = "multipart/form-data" })){
#Html.ValidationSummary(true)
<fieldset>
<legend>myImage</legend>
#Html.EditorForModel();
<div class="editor-label">Image</div>
<div class="editor-field">
#if (Model.Data != null)
{
<img src="#Url.Action("show", new { id = Model.imageID })" height="150" width="150" />
}
else {
#:None
}
</div>
<p>
<span>Choose a new file</span> <input type="file" name="imgFile"/>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
When I run the application it throws an error saying "Object reference not set to an instance of an object."
Any suggestions on how to fix the problems will be appriciated! By the way, the create and details method are all working. I think it has to do with data binding, but I'm not sure... I have no clue how to fix it.
Finally fixed the problem based on the advice from Eulerfx
here is the working action.
[HttpPost]
public ActionResult Edit(myImage img, HttpPostedFileBase imageFile)
{
myImage imgToSave = (from imga in db.myImages
where imga.imageID == img.imageID
select imga).First();
if (ModelState.IsValid)
{
if (img != null)
{
imgToSave.imageType = imageFile.ContentType;
var binaryReader = new BinaryReader(imageFile.InputStream);
imgToSave.Data = binaryReader.ReadBytes(imageFile.ContentLength);
binaryReader.Close();
}
TryUpdateModel(imgToSave);
db.SubmitChanges();
return RedirectToAction("Index");
}
else
{
// there is something wrong with the data values
return View(img);
}
}
The problem may be that the name of the file input field in the HTML is imgeFile and the name of the file parameter in MVC is imageFile. Ensure that the input field name and the action method parameter names match.

Resources