You've got a number of issues, some major, some minor.
First and foremost, you're using the extension method wrong. The whole point of adding an extension is that it becomes a method off an instance of that type. The this
keyword param, is implicit, and is filled by the back-referencing the object the method is called from, not passed explicitly. In other words, what you should have for your conditional is:
if (file.IsImage())
{
...
Notice also that there's no comparison with true
. While there's nothing wrong with that, it's completely unnecessary, you already have a boolean.
Second, while placing this conditional around the rest of the code should be effective to prevent the object being saved, it provides no guidance to the user. Instead, you should do something like:
if (!file.IsImage())
{
ModelState.AddModelError("file", "Upload must be an image");
}
if (ModelState.IsValid)
{
...
By adding an error to ModelState
, not only do you cause IsValid
to be false, but now an actual error message will be presented to the user when the form is returned again.
Third, by attempting to select an existing profile instance from the database, you'll either get that instance or null. Therefore, you don't need to check whether ProfileId
is 0, which is a pretty fragile check anyways (a user could merely change the hidden field's value to something else to modify an existing item). Instead, just do:
var dbEntry = context.Profiles.Find(profile.ProfileID);
if (dbEntry == null)
{
// add profile
}
else
{
// update profile
}
Fifth, you're never doing anything with file
. At some point, you should be doing something like:
var binaryReader = new BinaryReader(file.InputStream);
dbEntry.ImageData = binaryReader.ReadBytes(file.InputStream.Length);
dbEntry.ImageMimeType = file.ContentType;
Finally, and this is more stylistic than anything, but excessive use of else
blocks that are unnecessary makes your code harder to read. You can simply let the error case fall through. For example:
if (!file.IsImage())
{
ModelState.AddModelError("file", "Upload must be an image");
}
if (ModelState.IsValid)
{
// save profile and redirect
}
return View(profile);
The first conditional will either add an error or not to ModelState
. Then, in the second conditional, the code will only run if there's no errors, then it returns, so you never hit the final return View(profile)
. However, if there's any validation errors, you just fall through to that final return. No else
is necessary, and the code is much more concise and readable.