MVC File Upload - Saving path and filename back to database - asp.net-mvc

Not sure where the issue is - the file upload is working fine and going to the correct folder however the path and filename are not being stored in the database.
I want to use this so that I can add links to my index view for each document uploaded.
Any help on this would be brilliant as I have been racking my brains for 2 days over this.
Regards
Andy
Model:
namespace inventIT.Models
{
using System;
using System.Collections.Generic;
public partial class ComputerInventory
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public ComputerInventory()
{
this.ComputerInstallations = new HashSet<ComputerInstallation>();
}
public int RecordID { get; set; }
public string ComputerAdName { get; set; }
public string ComputerBrand { get; set; }
public string ComputerModel { get; set; }
public string ComputerSerialNumber { get; set; }
public string ComputerOS { get; set; }
public System.DateTime ComputerPurchaseDate { get; set; }
public string ComputerAddedBy { get; set; }
public Nullable<bool> ComputerArchived { get; set; }
public Nullable<System.DateTime> ComputerArchivedDate { get; set; }
public string FileDesc { get; set; }
public string FileName { get; set; }
public string Extension { get; set; }
public Nullable<int> FileID { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ComputerInstallation> ComputerInstallations { get; set; }
public virtual Lookup Lookup { get; set; }
public virtual Lookup Lookup1 { get; set; }
public virtual ITTeamLookup ITTeamLookup { get; set; }
public virtual Lookup Lookup2 { get; set; }
}
}
Controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using inventIT.Models;
namespace inventIT.Controllers
{
public class ComputerInventoriesController : Controller
{
private HAWKTRAINING_INVENTITEntities db = new HAWKTRAINING_INVENTITEntities();
// GET: ComputerInventories
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page, int? PageSize)
{
ViewBag.searchString = "";
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var AssessorIDs = from s in db.ComputerInventories
select s;
if (!String.IsNullOrEmpty(searchString))
{
AssessorIDs = AssessorIDs.Where(s => s.ComputerAdName.Contains(searchString) || searchString == null || searchString == "");
}
switch (sortOrder)
{
case "name_desc":
AssessorIDs = AssessorIDs.OrderByDescending(s => s.ComputerAdName);
break;
case "Date":
AssessorIDs = AssessorIDs.OrderBy(s => s.ComputerPurchaseDate);
break;
case "date_desc":
AssessorIDs = AssessorIDs.OrderByDescending(s => s.ComputerPurchaseDate);
break;
default: // Name ascending
AssessorIDs = AssessorIDs.OrderBy(s => s.ComputerAdName);
break;
}
var computerInventories = db.ComputerInventories.Include(c => c.Lookup).Include(c => c.Lookup1).Include(c => c.ITTeamLookup).Include(c => c.Lookup2);
return View(computerInventories.Where(s => s.ComputerAdName.Contains(searchString) || searchString == null || searchString == "").OrderByDescending(c => c.ComputerAdName).ToList());
}
// GET: ComputerInventories/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ComputerInventory computerInventory = db.ComputerInventories.Find(id);
if (computerInventory == null)
{
return HttpNotFound();
}
return View(computerInventory);
}
// GET: ComputerInventories/Create
public ActionResult Create()
{
ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
return View();
}
// POST: ComputerInventories/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "RecordID,ComputerAdName,ComputerBrand,ComputerModel,ComputerSerialNumber,ComputerOS,ComputerPurchaseDate,ComputerAddedBy,ComputerArchived,ComputerArchivedDate,FileDesc,FileName,Extension,FileID")] ComputerInventory computerInventory)
{
if (ModelState.IsValid)
{
List<ComputerInventory> fileDetails = new List<ComputerInventory>();
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
ComputerInventory fileDetail = new ComputerInventory()
{
FileName = fileName,
Extension = Path.GetExtension(fileName),
FileID = computerInventory.RecordID
};
fileDetails.Add(fileDetail);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads/"), fileDetail.FileName);
file.SaveAs(path);
}
}
computerInventory.FileID = computerInventory.FileID;
computerInventory.Extension = computerInventory.Extension;
computerInventory.FileDesc = computerInventory.FileDesc;
computerInventory.FileName = computerInventory.FileName;
db.ComputerInventories.Add(computerInventory);
db.SaveChanges();
return RedirectToAction("Index");
}
if (ModelState.IsValid)
{
try
{
db.ComputerInventories.Add(computerInventory);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
return View("Error", new HandleErrorInfo(ex, "ComputerInventories", "Create"));
}
}
ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
return View(computerInventory);
}
[HttpPost]
[ValidateAntiForgeryToken]
// GET: ComputerInventories/Edit/5
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ComputerInventory computerInventory = db.ComputerInventories.Find(id);
if (computerInventory == null)
{
return HttpNotFound();
}
ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
return View(computerInventory);
}
// POST: ComputerInventories/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "RecordID,ComputerAdName,ComputerBrand,ComputerModel,ComputerSerialNumber,ComputerOS,ComputerPurchaseDate,ComputerAddedBy,ComputerArchived,ComputerArchivedDate,FileDesc,FileName,Extension,FileID")] ComputerInventory computerInventory)
{
if (ModelState.IsValid)
{
db.Entry(computerInventory).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
return View(computerInventory);
}
// GET: ComputerInventories/Delete/5
public ActionResult Delete(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ComputerInventory computerInventory = db.ComputerInventories.Find(id);
if (computerInventory == null)
{
return HttpNotFound();
}
return View(computerInventory);
}
// POST: ComputerInventories/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
ComputerInventory computerInventory = db.ComputerInventories.Find(id);
db.ComputerInventories.Remove(computerInventory);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
View
#model inventIT.Models.ComputerInventory
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Computer Assets</h2>
#using (Html.BeginForm("Create", "ComputerInventories", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Create</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ComputerAdName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ComputerAdName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ComputerAdName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerBrand, "ComputerBrand", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ComputerBrand", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ComputerBrand, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerModel, "ComputerModel", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ComputerModel", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ComputerModel, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerSerialNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ComputerSerialNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ComputerSerialNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerOS, "ComputerOS", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ComputerOS", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ComputerOS, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerPurchaseDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ComputerPurchaseDate, new { htmlAttributes = new { #class = "form-control jqueryui-marker-datepicker" } })
#Html.ValidationMessageFor(model => model.ComputerPurchaseDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerAddedBy, "ComputerAddedBy", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ComputerAddedBy", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ComputerAddedBy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerArchived, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.ComputerArchived)
#Html.ValidationMessageFor(model => model.ComputerArchived, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerArchivedDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ComputerArchivedDate, new { htmlAttributes = new { #class = "form-control jqueryui-marker-datepicker" } })
#Html.ValidationMessageFor(model => model.ComputerArchivedDate, "", new { #class = "text-danger" })
</div>
</div>
#Html.HiddenFor(x => x.FileDesc)
<input type="file" name="file" id="file" />
<input type="submit" value="submit" />

You seems to be missing Path property in your ComputerInventory and hence in your table too. you are not setting your path to any property . How do you expect it to be saved in database?
First add a column in Table as FilePath, update Model ComputerInventory and set path to this FilePath variable
Class ComputerInventory()
{
public string FilePath { get; set; }
//other properties;
}
computerInventory.FilePath = path;
db.ComputerInventories.Add(computerInventory);
db.SaveChanges();

Related

Unable to edit the user information in mvc

Here is my problem , So i wanted to only allowing the user to change/edit their password and username only.
My original model for customer is this
public string IC { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Username{ get; set; }
public string Password{ get; set; }
And this is my VM for the customer
public string Username{ get; set; }
public string Password{ get; set; }
And this is my controller for the edit function
public ActionResult Edit([Bind(Include = "Username,Password")] CustomersVM customersVM )
{
if (ModelState.IsValid)
{
db.Entry(customersVM ).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customersVM );
}
view.cshtml
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.IC)
<div class="form-group">
#Html.LabelFor(model => model.Username, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Username, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Username, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
So this VM is to let the ModelState goes valid, which is will going right into the database but it turn out to turn this type of error
System.InvalidOperationException: 'The entity type CustomerVM is not part of the model for the current context.'
In order to edit/update a record, you need to identify that record first. I your case, your ViewModel is not what your database holds but the first model in your question. So you need to map that viewModel to the real model before saving or fetch the existing record then modify it then set it as modified before saving.
public ActionResult Edit([Bind(Include = "Username,Password")] CustomersVM customersVM )
{
if (ModelState.IsValid)
{
var existing = db.Customers.FirstOrDefault(x => x.Id == customersVM.Id);
if (existing != null)
{
existing.Username = customersVM.Username;
existing.Password = customerVM.Password;
db.Entry(existing ).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(customersVM );
}

System.InvalidOperationException: 'The ViewData item that has the key 'X is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.'

I got this error when I want to Create my Contact. Need help I would be thankful.
My database SQL database table is connected via entity framework.
Home Controller / Create Action
[HttpGet]
public ActionResult Create()
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CountryStateContactViewModel csvm)
{
if (!ModelState.IsValid)
{
return View(csvm);
}
Contact model = new Contact()
{
CountryId = csvm.CountryId,
StateId = csvm.StateId,
ContactId = csvm.ContactId,
ImeOsobe = csvm.ImeOsobe
...and all other fields
};
db.Contacts.Add(model);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException db)
{
Exception raise = db;
foreach (var validationErrors in db.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("Index");
}
Now here is ViewModel
public int CountryId { get; set; }
[Required]
[Display(Name = "Naziv županije")]
public string CountryName { get; set; }
public int StateId { get; set; }
[Required]
[Display(Name = "Naziv općine")]
public string StateName { get; set; }
public int ContactId { get; set; }
public virtual Country Country { get; set; }
public virtual State State { get; set; }
....and all other fields
And finally here is "Create" view.
#model AkvizicijeApp_4_7.Models.CountryStateContactViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CountryId, htmlAttributes: new { #class = "control-label col-md-2"
})
<div class="col-md-10">
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select
Country--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StateId, htmlAttributes: new { #class = "control-label col-md-2"
})
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new {
#class = "form-control" })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CountryStateContactViewModel</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.ContactId, htmlAttributes: new { #class = "control-label
col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContactId, new { htmlAttributes = new { #class =
"form-control" } })
#Html.ValidationMessageFor(model => model.ContactId, "", new { #class = "text-danger"
})
</div>
</div>
And after that is all other fields and js for parent/child dropdown list.
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "
</option>")
});
});
})
});
</script>
Please help me solve my problem. <3

How to store and display SelectList data

I am using SelectList to populate dropdownlists in my view. It works for the Create and Edit views to store ID value data in a table. How do I retrieve the 'Name' value to display in a Details view?
Model
Public Class Employee {
[Key]
public int ID { get; set;}
public string UserName {get; set; }
public byte Gender { get; set; }
}
ViewModel
public class EmployeeEditViewModel {
public int ID { get; set; }
public string UserName { get; set; }
public SelectList GenderList { get; set; }
public EmployeeEditViewModel () {
GenderList = CommonHelper.GenderList(null);
}
}
Helper
public static SelectList GenderList(object selected)
{
return new SelectList(new[]
{
new { Value = 0, Name = "Male" },
new { Value = 1, Name = "Female" }
}
, "Value", "Name", selected);
}
Edit View
#model Models.ViewModel.EmployeeEditViewModel
#using (Html.BeginForm()) {
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.UserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GenderList, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Gender, Model.GenderList, "- Select -", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.GenderList, "", new { #class = "text-danger" })
</div>
</div>
}
Controller
[HttpPost]
public ActionResult CreateEmployee(EmployeeEditViewModel emProfile)
{
try
{
if (ModelState.IsValid)
{
Employee newUser = new Employee();
newUser.UserName = emProfile.UserName;
newUser.Gender = emProfile.Gender;
userRepository.Add(newUser);
userRepository.SaveChanges();
return RedirectToAction("Index");
}
}
catch (Exception ex)
{ }
return View(emProfile);
}
So far it works great, I am able to create, edit Employee records and 1 or 0 is stored in the table for the gender.
But when I want to display the employee data in a details view how do I get the text 'Male' or 'Female'?
I ended up creating a helper method to retrieve the text.
public static string GetTextFromSelectList(int id, string listName)
{
string selectedText = string.Empty;
SelectListItem selectedItem;
switch (listName)
{
case "Gender":
selectedItem = Helper.CommonHelper.GenderList(null).FirstOrDefault(x => x.Value == id.ToString());
selectedText = selectedItem == null ? null : selectedItem.Text;
break;
default:
selectedText = null;
break;
}
return selectedText;
}

controller do not hit when use AdditionalFields in remote validation

In product class i have code properties which need to be unique. I use remote validation. but it makes problem when editing. so i add AdditionalFields. it works fine when perform edit operation but product can not create now. it never hit controller when use AdditionalFields in remote validation..
My model:
public class Product
{
public int Id { get; set; }
[Remote("IsCodeAvailable", "Product", AdditionalFields ="Id", HttpMethod = "GET", ErrorMessage = "Product Code already taken")]
public string Code { get; set; }
public string Name { get; set; }
}
here is my validation code
[HttpGet]
public JsonResult IsCodeAvailable(string code, int Id)
{
try
{
var flag = true;
if (Id == 0) // its a new object
{
flag = !db.Product.Any(x => x.Code == code);
}
else // its an existing object so exclude existing objects with the id
{
flag = !db.Product.Any(x => x.Code == code && x.Id != Id);
}
return Json(flag, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
and here is my view
<div class="form-horizontal">
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Code, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Code, new { htmlAttributes = new { #class = "form-control", #required = "required", #style = "text-transform:uppercase" } })
#Html.ValidationMessageFor(model => model.Code, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
Any kind of help will be greatly appreciated

MVC how to retrieve the current date and time in a view

I have been looking for a while now and can't seem to find the answer. What I am trying to do is have the current date and the current Time in two fields on a create page. This page will be used for basic journey scheduling.
What I have so far is my model
public class Journey
{
public int JourneyId { get; set; }
public string Name { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}",ApplyFormatInEditMode = true)]
public DateTime Departure { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString="{0:hh\\:mm}", ApplyFormatInEditMode = true)]
public TimeSpan DepartureTime { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime Arrival { get; set; }
public string Description { get; set; }
public int FareId { get; set; }
public int TrainId { get; set; }
public virtual FareType FareType { get; set; }
public virtual Train Train { get; set; }
}
Account Controller
public class JourneyController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
//
// GET: Journey
public ActionResult Index()
{
return View(db.Journey.ToList());
}
//
// GET: Journey/Create
public ActionResult Create()
{
ViewBag.TrainId = new SelectList(db.Train, "TrainId", "Name");
return View();
}
// POST: Journey/Create
[HttpPost]
public ActionResult Create(Journey model)
{
try
{
if (ModelState.IsValid)
{
db.Journey.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.TrainId = new SelectList(db.Train, "TrainId", "Name", model.TrainId);
return RedirectToAction("Index");
}
catch (DataException)
{
ModelState.AddModelError("", "Sorry something went wrong");
}
return View(model);
}
}
And finaly my view
<div class="form-horizontal">
<h4>Journey</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Departure, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Departure, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Departure, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DepartureTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DepartureTime., new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DepartureTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Arrival, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Arrival, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Arrival, "", new { #class = "text-danger" })
</div>
</div>
Any help would be great
Many thanks
Use custom getters and setters on your DateTime property to provide a default of now:
private DateTime? departure;
public DateTime Departure
{
get { return departure ?? DateTime.Today; }
set { departure = value; }
}
private DateTime? departureTime;
public DateTime DepartureTime
{
get { return departureTime ?? DateTime.Now; }
set { departureTime = value; }
}
private DateTime? arrival;
public DateTime Arrival
{
get { return arrival ?? DateTime.Today; }
set { arrival = value; }
}
Alternatively, you can just manually set the values in your action:
public ActionResult Create()
{
var journey = new Journey
{
Departure = DateTime.Today,
DepartureTime = DateTime.Now,
Arrival = DateTime.Today
};
ViewBag.TrainId = new SelectList(db.Train, "TrainId", "Name");
return View(journey);
}

Resources