uploading pictures in application and saving path in database for MVC - asp.net-mvc

i m stuck with uploading 3pictures, please suggest how can i move ahead
if you want i can email or upload my full solution for you guys
below is few detail:
My Controller:
namespace TiresalesClaim.Controllers
{
public class TsiclaimsController : Controller
{
private TiresalesClaimContext db = new TiresalesClaimContext();
// GET: Tsiclaims
public ActionResult Index(string searchBy, string search, int? page)
{
// var claims = db.Tsiclaims.Include(d => d.disposition).ToList();
if (searchBy == "DistributorName")
{
return View(db.Tsiclaims.Where(x => x.DistributorName.Contains(search) || search == null)
.ToList().ToPagedList(page ?? 1, 20));
}
else
if (searchBy == "TyreSize")
{
return View(db.Tsiclaims.Where(x => x.TyreSize.Contains(search) || search == null)
.ToList().ToPagedList(page ?? 1, 20));
}
else
if (searchBy == "TyreBrand")
{
return View(db.Tsiclaims.Where(x => x.TyreBrand.Contains(search) || search == null)
.ToList().ToPagedList(page ?? 1, 20));
}
else
if (searchBy == "Disposition")
{
return View(db.Tsiclaims.Where(x => x.DispositionAsPerTSI.Contains(search) || search == null)
.ToList().ToPagedList(page ?? 1, 20));
}
else
{
return View(db.Tsiclaims.ToList().ToPagedList(page ?? 1, 20));
}
}
public ActionResult OrderByDistributorName(int? page)
{
var claim = from c in db.Tsiclaims
orderby c.DistributorName ascending
select c;
return View((claim).ToPagedList(page ?? 1, 20));
}
public ActionResult OrderBySize(int? page)
{
var claim = from c in db.Tsiclaims
orderby c.TyreSize ascending
select c;
return View((claim).ToPagedList(page ?? 1, 20));
}
public ActionResult OrderByBrand(int? page)
{
var claim = from c in db.Tsiclaims
orderby c.TyreBrand ascending
select c;
return View((claim).ToPagedList(page ?? 1, 20));
}
public ActionResult OrderByDisposition(int? page)
{
var claim = from c in db.Tsiclaims
orderby c.DispositionAsPerTSI descending
select c;
return View((claim).ToPagedList(page ?? 1, 20));
}
public ActionResult OrderByDate(int? page)
{
var claim = from c in db.Tsiclaims
orderby c.ClaimRecDate descending
select c;
return View((claim).ToPagedList(page ?? 1, 20));
}
// GET: Tsiclaims/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tsiclaim tsiclaim = db.Tsiclaims.Find(id);
if (tsiclaim == null)
{
return HttpNotFound();
}
return View(tsiclaim);
}
// GET: Tsiclaims/Create
public ActionResult Create()
{
TableDbContext tdb = new TableDbContext();
ViewBag.distributor = new SelectList(tdb.DistributorNames, "Name", "Name");
ViewBag.size = new SelectList(tdb.TyreSizes, "Name", "Name");
ViewBag.brand = new SelectList(tdb.TyreBrands, "Name", "Name");
ViewBag.Dispo = new SelectList(tdb.DispositionAsPerTSIs, "Name", "Name");
return View();
}
// POST: Tsiclaims/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,DistributorName,ClaimRecDate,State,Country,TelNo,FaxNo,Email,TyreSize,TyreBrand,TyreSerialNo,RemainingTreadDept,TreadWear,DefectAsPerDistributor,TypeofTyreWear,DefectAsPerTSI,DispositionAsPerTSI,ClaimValueAwarded,InspectedBy,Picture1,Picture2,Picture3")] Tsiclaim tsiclaim)
{
if (ModelState.IsValid)
{
db.Tsiclaims.Add(tsiclaim);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(tsiclaim);
}
// GET: Tsiclaims/Edit/5
public ActionResult Edit(int? id)
{
TableDbContext tdb = new TableDbContext();
ViewBag.distributor = new SelectList(tdb.DistributorNames, "Name", "Name");
ViewBag.size = new SelectList(tdb.TyreSizes, "Name", "Name");
ViewBag.brand = new SelectList(tdb.TyreBrands, "Name", "Name");
ViewBag.Dispo = new SelectList(tdb.DispositionAsPerTSIs, "Name", "Name");
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tsiclaim tsiclaim = db.Tsiclaims.Find(id);
if (tsiclaim == null)
{
return HttpNotFound();
}
return View(tsiclaim);
}
// POST: Tsiclaims/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,DistributorName,ClaimRecDate,State,Country,TelNo,FaxNo,Email,TyreSize,TyreBrand,TyreSerialNo,RemainingTreadDept,TreadWear,DefectAsPerDistributor,TypeofTyreWear,DefectAsPerTSI,DispositionAsPerTSI,ClaimValueAwarded,InspectedBy,Picture1,Picture2,Picture3")] Tsiclaim tsiclaim)
{
if (ModelState.IsValid)
{
db.Entry(tsiclaim).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(tsiclaim);
}
// GET: Tsiclaims/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tsiclaim tsiclaim = db.Tsiclaims.Find(id);
if (tsiclaim == null)
{
return HttpNotFound();
}
return View(tsiclaim);
}
// POST: Tsiclaims/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Tsiclaim tsiclaim = db.Tsiclaims.Find(id);
db.Tsiclaims.Remove(tsiclaim);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
My Create Page:
#model TiresalesClaim.Models.Tsiclaim
#
{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#*<h1>Tire Sales International</h1>*#
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#*<div class="form-group">
#Html.LabelFor(model => model.Id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DisplayFor(model => model.Id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Id, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
#Html.LabelFor(model => model.DistributorName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.DistributorName, (SelectList)ViewBag.distributor, "Select Distributor")
#*#Html.DropDownList("DistributorName", new List<SelectListItem> {
new SelectListItem{Text="Al Alaly Tyre", Value="Al Alaly Tyre"},
new SelectListItem{Text="Jilphar", Value="Jilphar"}
}, "Select Distributor Name")*#
#*#Html.EditorFor(model => model.DistributorName, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.DistributorName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ClaimRecDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ClaimRecDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ClaimRecDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.State, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.State, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.State, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Country, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Country, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Country, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TelNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TelNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TelNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FaxNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FaxNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FaxNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TyreSize, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TyreSize, (SelectList)ViewBag.size, "Select Tyre Size")
#*#Html.DropDownList("TyreSize", new List<SelectListItem> {
new SelectListItem{Text="GD 1200r24 20pr HF702", Value="GD 1200r24 20pr HF702"},
new SelectListItem{Text="GD 1200r24 20pr GD122", Value="GD 1200r24 20pr GD122"},
new SelectListItem{Text="TF 1200r24 20pr TF801", Value="TF 1200r24 20pr TF801"},
new SelectListItem{Text="TF 1200r24 20pr TF580", Value="TF 1200r24 20pr TF580"},
new SelectListItem{Text="YG 1200r24 20pr FH326", Value="YG 1200r24 20pr FH326"},
new SelectListItem{Text="GD 315/80r22.5 18pr GD660", Value="GD 315/80r22.5 18pr GD660"},
new SelectListItem{Text="GD 315/80r22.5 18pr GD768", Value="GD 315/80r22.5 18pr GD768"},
new SelectListItem{Text="YG 315/80r22.5 18pr FH158", Value="YG 315/80r22.5 18pr FH158"},
new SelectListItem{Text="YG 315/80r22.5 18pr FH159", Value="YG 315/80r22.5 18pr FH159"},
new SelectListItem{Text="GD 385/65r22.5 20pr GD022", Value="GD 385/65r22.5 20pr GD022"},
new SelectListItem{Text="YG 385/65r22.5 20pr FH538", Value="YG 385/65r22.5 20pr FH538"},
}, "Select Tyre Size")*#
#*#Html.EditorFor(model => model.TyreSize, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.TyreSize, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TyreBrand, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TyreBrand, (SelectList)ViewBag.brand, "Select Tyre Brand")
#*#Html.DropDownList("TyreBrand", new List<SelectListItem> {
new SelectListItem{Text="GreenDragon Brand Tyre", Value="GreenDragon Brand Tyre"},
new SelectListItem{Text="Tuffstone Brand Tyre", Value="Tuffstone Brand Tyre"},
new SelectListItem{Text="Young Brand Tyre", Value="Young Brand Tyre"}
}, "Select Tyre Brand")*#
#*#Html.EditorFor(model => model.TyreBrand, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.TyreBrand, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TyreSerialNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TyreSerialNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TyreSerialNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RemainingTreadDept, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RemainingTreadDept, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RemainingTreadDept, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TreadWear, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TreadWear, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TreadWear, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DefectAsPerDistributor, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DefectAsPerDistributor, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DefectAsPerDistributor, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TypeofTyreWear, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TypeofTyreWear, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TypeofTyreWear, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DefectAsPerTSI, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DefectAsPerTSI, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DefectAsPerTSI, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DispositionAsPerTSI, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model=>model.DispositionAsPerTSI,(SelectList)ViewBag.Dispo, "Select Disposition")
#*#Html.DropDownList("DispositionAsPerTSI", new List<SelectListItem> {
new SelectListItem{Text="Pass", Value="Pass"},
new SelectListItem{Text="Fail", Value="Fail"}
}, "Select Disposition As Per TSI")*#
#*#Html.EditorFor(model => model.DispositionAsPerTSI, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.DispositionAsPerTSI, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ClaimValueAwarded, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ClaimValueAwarded, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ClaimValueAwarded, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.InspectedBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.InspectedBy, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.InspectedBy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Picture1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Picture1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Picture1, "", new { #class = "text-danger" })
<input type="file" class="form-control" id="Picture1"/>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Picture2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Picture2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Picture2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Picture3, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Picture3, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Picture3, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
#*<input type="submit" value="Create" class="btn btn-default" />*#
<input type="image" src="~/Icons/Save.png" alt="Submit" width="40" height="40">
</div>
</div>
</div>}<div><img src="#Url.Content("~/Icons/go-back-icon.png")" width="50" />Back</div>#section Scripts {#Scripts.Render("~/bundles/jqueryval")}
My Model:
namespace TiresalesClaim.Models
{
public class Tsiclaim
{
[Key]
[DisplayName("Claim Ref#")]
public int Id { get; set; }
//[Key]
//[Range(1,999999)]
//public int Id { get; set; }
[Required]
[DisplayName("Distributor Name")]
public string DistributorName { get; set; }
[DataType(DataType.Date)]
[DisplayName("Claim Rec Date")]
public DateTime ClaimRecDate { get; set; }
[Required]
[DisplayName("State")]
public string State { get; set; }
[Required]
[DisplayName("Country")]
public string Country { get; set; }
[DataType(DataType.PhoneNumber)]
[DisplayName("Tel #")]
public string TelNo { get; set; }
[DisplayName("Fax #")]
[DataType(DataType.PhoneNumber)]
public string FaxNo { get; set; }
[DisplayName("Email")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required]
[DisplayName("Tyre Size")]
public string TyreSize { get; set; }
[Required]
[DisplayName("Tyre Brand")]
public string TyreBrand { get; set; }
//[Required]
//public string PlyRating { get; set; }
[Required]
[DisplayName("Tyre Serial #")]
public string TyreSerialNo { get; set; }
[Required]
[DisplayName("Rmaining Tread Dept")]
public decimal RemainingTreadDept { get; set; }
[Required]
[DisplayName("% Tread Wear")]
public decimal TreadWear { get; set; }
[Required]
[DisplayName("Defect As Per Distributor")]
public string DefectAsPerDistributor { get; set; }
[Required]
[DisplayName("Type of Tyre Wear")]
public string TypeofTyreWear { get; set; }
[Required]
[DisplayName("Defect As Per TSI")]
public string DefectAsPerTSI { get; set; }
[Required]
[DisplayName("Disposition As Per TSI")]
public string DispositionAsPerTSI { get; set; }
[Required]
[DisplayName("% Claim Value Awarded")]
public decimal ClaimValueAwarded { get; set; }
[Required]
[DisplayName("Inspected By")]
public string InspectedBy { get; set; }
[DataType(DataType.Upload)]
public string Picture1 { get; set; }
[DataType(DataType.Upload)]
public string Picture2 { get; set; }
[DataType(DataType.Upload)]
public string Picture3 { get; set; }
[DisplayName("Status")]
public string Status { get; set; }
[DisplayName("Remarks")]
public string Remarks { get; set; }
//[NotMapped]
//public virtual DispositionAsPerTSI disposition { get; set; }
}
}

You need to get the file data from object containing the file data, i.e. HttpPostedFileBase. You can then get the data and the fully qualified name/path and save them separately as needed.
See this link for an example: Uploading a File (Or Files) With ASP.NET MVC
Here is a quick example:
VIEW:
<form action="" method="post" enctype="multipart/form-data">
<label for="file1">Filename:</label>
<input type="file" name="files" id="file1" />
<label for="file2">Filename:</label>
<input type="file" name="files" id="file2" />
<input type="submit" />
</form>
CONTROLLER:
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}

Related

MVC- need help for creating "Edit" View

need help about creating Edit view. I made create view and I need to be able to edit my entry sometimes. I used entity framework for connect with sql.
```
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, PrezimeOsobe = csvm.PrezimeOsobe, Komentar = csvm.Komentar, Email = csvm.Email, Aktivan = csvm.Aktivan, kcbr = csvm.kcbr, KucniBroj = csvm.KucniBroj, NazivUlice = csvm.NazivUlice, NazivNaselja = csvm.NazivNaselja, PostanskiBroj = csvm.PostanskiBroj, KontaktBroj = csvm.KontaktBroj };
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");
This is Create View where I am adding new Contact from CountryStateContactViewModel (All three tables in one VIEW with 2 connected dropdown lists )
#model AkvizicijeApp_4_2.Models.CountryStateContactViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CountryStateContactViewModel</h4>
<hr />
#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 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>
<div class="form-group">
#Html.LabelFor(model => model.PostanskiBroj, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PostanskiBroj, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PostanskiBroj, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NazivNaselja, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NazivNaselja, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NazivNaselja, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NazivUlice, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NazivUlice, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NazivUlice, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.KucniBroj, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.KucniBroj, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.KucniBroj, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.kcbr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.kcbr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.kcbr, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Aktivan, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Aktivan)
#Html.ValidationMessageFor(model => model.Aktivan, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImeOsobe, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ImeOsobe, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ImeOsobe, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PrezimeOsobe, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PrezimeOsobe, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PrezimeOsobe, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.KontaktBroj, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.KontaktBroj, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.KontaktBroj, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Komentar, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Komentar, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Komentar, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
#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>
And finally CountryStateContactViewModel, Where is id-s from first 2 tables(dropdowns) and all fields from third table.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AkvizicijeApp_4_2.Models
{
public class CountryStateContactViewModel
{
public int CountryId { get; set; }
public int StateId { get; set; }
public int ContactId { get; set; }
public int PostanskiBroj { get; set; }
public string NazivNaselja { get; set; }
public string NazivUlice { get; set; }
public string KucniBroj { get; set; }
public string kcbr { get; set; }
public bool Aktivan { get; set; }
public string ImeOsobe { get; set; }
public string PrezimeOsobe { get; set; }
public string KontaktBroj { get; set; }
public string Email { get; set; }
public string Komentar { get; set; }
}
}
Pls help me from that code (from Create View) to make Edit View (Where I can change entries
)
Thanks alot. ;)
Edit view is almost the same... the only missing property is Id:
public class EditStateContactViewModel : CountryStateContactViewModel
{
public int Id {get;set;}
}
public ActionResult Edit(int Id)
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
ViewBag.Id = Id;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(EditStateContactViewModel csvm)
{
if (!ModelState.IsValid)
return View(csvm);
var item = db.Contacts.First(x=>x.Id = csvm.Id);
item.CountryId = csvm.CountryId;
item.StateId = csvm.StateId;
item.ImeOsobe = csvm.ImeOsobe;
item.PrezimeOsobe= csvm.PrezimeOsobe;
item.Komentar = csvm.Komentar ;
item.Email = csvm.Email;
item.Aktivan = csvm.Aktivan ;
item.kcbr = csvm.kcbr;
item.KucniBroj = csvm.KucniBroj;
item.NazivUlice = csvm.NazivUlice ;
item.NazivNaselja = csvm.NazivNaselja ;
item.PostanskiBroj = csvm.PostanskiBroj ;
item.KontaktBroj = csvm.KontaktBroj ;
db.Contacts.Update(item);
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");
And View:
#model AkvizicijeApp_4_2.Models.EditStateContactViewModel
#using (Html.BeginForm())
{
#Html.HiddenFor(x=>x.Id)
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Edit CountryStateContactViewModel</h4>
<hr />
#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>
#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>

Another [Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot perform runtime binding on a null reference'] in ASP.NET MVC

I tried to have a file upload into another folder, it works fine when it directly add to the database, but if I try to use it with MultipleDocumentCreateClass for the stored procedure, I get this error:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot perform runtime binding on a null reference'
Controller
// GET: Activity/DocumentNew
public ActionResult DocumentNew(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Hoạt_động hoạt_động = db.Hoạt_động.Find(id); ;
ViewBag.act = hoạt_động;
if (hoạt_động == null)
{
return HttpNotFound();
}
MultipleDocumentCreateClass mtd = new MultipleDocumentCreateClass();
mtd.Mã_Hoạt_động = hoạt_động.Mã_Hoạt_động;
Dropdownlist2();
return View(mtd);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DocumentNew([Bind(Include = "Mã_Hoạt_động, Tên, Loại,Thông_tin, Nội_dung")]MultipleDocumentCreateClass mt)
{
if (ModelState.IsValid)
{
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
//Save into folder
file.SaveAs(Server.MapPath("/App_Data/Video/" + fileName));
mt.Nội_dung = "~/App_Data/Video/" + fileName;
mt.Tên = Path.GetFileNameWithoutExtension(file.FileName);
}
db.MultipleDocCr(mt.Mã_Hoạt_động, mt.Tên, mt.Loại, mt.Thông_tin, mt.Nội_dung);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(mt);
}
MultipleDocumentUseClass:
public class MultipleDocumentCreateClass
{
public Nullable<int> Mã_Hoạt_động { get; set; }
public string Tên { get; set; }
public string Loại { get; set; }
public string Thông_tin { get; set; }
public string Nội_dung { get; set; }
}
View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Hoạt động: #Model.Mã_Hoạt_động</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Mã_Hoạt_động, new { value = ViewBag.act.Mã_Hoạt_động })
<dt>
Hoạt động:
#ViewBag.act.Tên
</dt>
<div class="form-group">
#Html.LabelFor(model => model.Loại, "Thể loại", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Loại, new SelectList(ViewBag.doc, "Value", "Text"), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Loại, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Thông_tin, "Thông tin", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Thông_tin, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Thông_tin, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Nội_dung, "Chọn File", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Nội_dung, new { htmlAttributes = new { Type = "file" } })
#Html.ValidationMessageFor(model => model.Nội_dung, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Lưu" class="btn btn-default" />
</div>
</div>
</div>
}
The error points to this line
#Html.HiddenFor(model => model.Mã_Hoạt_động, new { value = ViewBag.act.Mã_Hoạt_động })
but when I add value manually without uploading, it works fine.
So the answer at the #using (Html.BeginForm()) in View
Change it into this #using (Html.BeginForm("DocumentNew", "Activity", FormMethod.Post, new { enctype = "multipart/form-data" }))

POST form in MVC - No Values being written to DB

I have a model that I'm trying to edit with a form:
public class Basiclife
{
[Key]
public int Id { get; set; }
public int? ResponseId { get; set; }
public string Plantype { get; set; }
public int Enrolledftes { get; set; }
public decimal Pctemployer { get; set; }
public decimal Fixedbenamt { get; set; }
public decimal Salarymult { get; set; }
public decimal Bencap { get; set; }
}
And a view wrapper to edit it (with the editor in a separate partial view):
<h2>CreateBasicLifeResponse</h2>
<div id="planList">
#using (Html.BeginForm("CreateBasicLifeResponse", "Surveys"))
{
<div id="editorRows">
#foreach (var item in Model.basiclives)
{
#Html.Partial("_BasicLifeResponse", item)
}
</div>
#Html.ActionLink("Add", "BasicLifeResponse", null, new { id = "addItem", #class = "button" });
<input type="submit" value="submit" />
}
</div>
The wrapper's model is:
public class ResponseBasicLife
{
public Response response { get; set; }
public List<Basiclife> basiclives { get; set; }
}
Here's the partial view:
#using CustomSurveyTool.Models
#model Basiclife
<div class="editorRow">
#using (Html.BeginCollectionItem("basiclives"))
{
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Plantype, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Plantype, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Plantype, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Enrolledftes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Enrolledftes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Enrolledftes, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Pctemployer, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Pctemployer, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Pctemployer, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Fixedbenamt, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Fixedbenamt, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Fixedbenamt, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Salarymult, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Salarymult, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Salarymult, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Bencap, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Bencap, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Bencap, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
X
</div>
</div>
}
</div>
Here's my controller action where I'm getting the proper responseId and assigning it to the form values:
public ActionResult CreateBasicLifeResponse(ResponseBasicLife model)
{
for (var i = 1; i < model.basiclives.Count; i++)
{
string currentUserId = User.Identity.GetUserId();
Response targetresponse = db.response.FirstOrDefault(x => x.Userid == currentUserId);
int responseid = targetresponse.Id;
model.basiclives[i].ResponseId = responseid;
db.basiclife.Add(model.basiclives[i]);
db.SaveChanges();
}
ResponseBasicLife basicliferesponse = new ResponseBasicLife
{
basiclives = new List<Basiclife>
{
new Basiclife { }
}
};
return View(basicliferesponse);
}
The only thing that's being written to the database is the ResponseID. How do I get the rest of the values to write to it?
This is a unique case where EditorFor could help. Essentially an object will have its editor template which is kind of like a partial view but specific to editing forms.
Secondly, the being form you are specifying is expecting the model of the view that you specified - in your case the viewWrapper. If for instance you specified a List<BasicLife>, then that is what the postBack shall be expecting, and not the BasicLife object. Below is how your postback would look like.
[HttpPost]
public ActionResult CreateBasicLifeResponse(List<BasicLife> model){
//your code goes here
}
From your view though, it looks clear that Model contains more than just a list. That is what shall be expected from the callback.

MVC 5 Code First Editing

Hey guys i am coding in MVC 5 code first now i have this table below when i want to edit a Cell number or an email and my changes are saved on the database my Picture got deleted i do not know why because i did not change it. every time i Edit other information the Picture got delete when i save my changes
[Key]
public int Member_Id { get; set; }
[Required]
[StringLength(20, MinimumLength = 3, ErrorMessage = "Please enter minimum of 3 characters")]
[RegularExpression(#"^[a-zA-Z\s?]+$", ErrorMessage = "Pease enter valid name!")]
[Display(Name = "First Name")]
public string Name { get; set; }
[Required]
[RegularExpression(#"^[a-zA-Z\s?]+$", ErrorMessage = "Pease enter valid Surname!")]
[StringLength(20, MinimumLength = 3, ErrorMessage = "Please enter minimum of 3 characters")]
[Display(Name = "Surname")]
public string Surname { get; set; }
[Required]
[RegularExpression(#"^(\d{10})$", ErrorMessage = "Cellphone number must be 10 digits!")]
[Display(Name = "Cell Number")]
public string Cell_Number { get; set; }
[Required]
[RegularExpression(#"^(\d{13})$", ErrorMessage = "id must be 13 digits!")]
[Display(Name = "ID Number")]
public string ID_Number { get; set; }
[Required]
[RegularExpression(".+\\#.+\\..+", ErrorMessage = "Please enter a valid email address")]
[Display(Name = "Email Address")]
public string Email { get; set; }
[Required]
[Display(Name = "Physical Address")]
public string Address { get; set; }
[Display(Name = "Owner")]
public bool Owner { get; set; }
[Display(Name = "Driver")]
public bool Driver { get; set; }
[Display(Name = "Rank Manager")]
public bool Rank_Manager { get; set; }
[Display(Name = "Profile Picture")]
public byte[] Picture { get; set; }
public string alter_Text { get; set; }
public string ImageMimeType { get; set; }
public virtual ICollection<Taxi> Taxi { get; set; }
and this is my controller
public ActionResult EditPick(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Member member = db.Member.Find(id);
if (member == null)
{
return HttpNotFound();
}
return View(member);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditPick(/*[Bind(Include = "Member_Id,Name,Surname,Cell_Number,ID_Number,Email,Address,Owner,Driver,Rank_Manager,Picture,alter_Text,ImageMimeType")]*/ Member member,HttpPostedFileBase image)
{
try
{
var picturee = new Member();
if (image != null)
{
if (image.ContentLength > 2 * 1024 * 1024)
{
ModelState.AddModelError("CustomError", "The File size be not more than 2 MB");
return View();
}
if (!(image.ContentType == "image/jpeg" || image.ContentType == "image/gif"))
{
ModelState.AddModelError("CustomError", "The File Allowed : jpeg and gif");
return View();
}
if (image != null)
{
member.ImageMimeType = image.ContentType;
member.Picture = new byte[image.ContentLength];
image.InputStream.Read(member.Picture, 0, image.ContentLength);
}
}
picturee.Member_Id = member.Member_Id;
picturee.Name = member.Name;
picturee.Surname = member.Surname;
picturee.Cell_Number = member.Cell_Number;
picturee.ID_Number = member.ID_Number;
picturee.Email = member.Email;
picturee.Address = member.Address;
picturee.Owner = member.Owner;
picturee.Driver = member.Driver;
picturee.Rank_Manager = member.Rank_Manager;
picturee.Picture = member.Picture;
picturee.ImageMimeType = member.ImageMimeType;
picturee.alter_Text = member.alter_Text;
db.Entry(picturee).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DataException)
{
ModelState.AddModelError("", "Sorry can not update contact Administrator");
}
return View(member);
}
This is my View when posting
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Member</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Member_Id)
<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.Surname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Surname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Surname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Cell_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Cell_Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Cell_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ID_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ID_Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ID_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Owner, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Owner)
#Html.ValidationMessageFor(model => model.Owner, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Driver, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Driver)
#Html.ValidationMessageFor(model => model.Driver, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Rank_Manager, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Rank_Manager)
#Html.ValidationMessageFor(model => model.Rank_Manager, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Picture, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#{
if (Model.Picture != null)
{
string imageBase64 = Convert.ToBase64String(Model.Picture);
string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
<img src="#imageSrc" width="100" height="100" />
}
}
#Html.ValidationMessageFor(model => model.Picture, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.alter_Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.alter_Text, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.alter_Text, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImageMimeType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ImageMimeType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ImageMimeType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
As said in comments, you need to add a Input=File Name=Image in your view to post back the file with the changes to your profile picture, but the most important thing to do, is to read back the member info from you database and not build a new one instance of a member.
Actually your new member has no info on the previous image if the view don't post back a file and when you save you loose the image bytes.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditPick(Member member,HttpPostedFileBase image)
{
try
{
var picturee = new context.Member.Find(member.Member_Id);
if(picturee != null)
{
.....
}
// Now you can start updating the other fields and then save.
// This is not needed -> picturee.Member_Id = member.Member_Id;
picturee.Name = member.Name;
picturee.Surname = member.Surname;
....
In this way you reload the image bytes in case the View don't post back a file to read
In the view you need to add the appriate code to post back the profile image if the user want it updated.
<div class="form-group">
#Html.LabelFor(model => model.Picture, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="Image" type="file" />
</div>
#{
if (Model.Picture != null)
{
string imageBase64 = Convert.ToBase64String(Model.Picture);
string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
<img src="#imageSrc" width="100" height="100" />
}
}
#Html.ValidationMessageFor(model => model.Picture, "", new { #class = "text-danger" })
</div>

How create single create action for multiple models with TPH approach

I have base class Contract
public abstract class Contract
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ContractID { get; set; }
[DataType(DataType.Date)]
[Required]
public DateTime StartDate { get; set; }
[DataType(DataType.Date)]
[Required]
public DateTime EndDate { get; set; }
}
And two other classes derive from this class: CreditContract and PrepaymentContract.
public class CreditContract : Contract
{
[Required]
public float CreditLimit { get; set; }
[Column(TypeName = "char")]
[StringLength(3)]
[Required]
public string CreditLimitCurrency { get; set; }
}
public class PrepaymentContract : Contract
{
[Required]
public float PrepaymentAmount { get; set; }
[Column(TypeName = "char")]
[StringLength(1)]
[Required]
public string PrepaymentPeriod { get; set; }
}
Additionally I've created ContractViewModel class.
public int SelectedContract { get; set; }
public CreditContract creditContract { get; set; }
public PrepaymentContract prepaymentContract { get; set; }
My Create method looks like this:
public ActionResult Create(ContractViewModel contract)
{
if (contract.SelectedCategory == 1)
{
if (ModelState.IsValid)
{
contract.creditContract.StartDate = contract.StartDate;
contract.creditContract.EndDate = contract.EndDate;
db.Contracts.Add(contract.creditContract);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(contract.creditContract);
}
else
{
if (ModelState.IsValid)
{
contract.prepaymentContract.StartDate = contract.StartDate;
contract.prepaymentContract.EndDate = contract.EndDate;
db.Contracts.Add(contract.prepaymentContract);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(contract.prepaymentContract);
}
}
And my Create view looks like this:
#model CodeFirstInheritance.ViewModels.ContractViewModel
<div class="form-horizontal">
<h4>Course</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.creditContract.StartDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.creditContract.StartDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.creditContract.StartDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.creditContract.EndDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.creditContract.EndDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.creditContract.EndDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SelectedCategory, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SelectedCategory, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SelectedCategory, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.creditContract.CreditLimit, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.creditContract.CreditLimit, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.creditContract.CreditLimit, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.creditContract.CreditLimitCurrency, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.creditContract.CreditLimitCurrency, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.creditContract.CreditLimitCurrency, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
Can I do something like that:
E.g:
var selectedContract = contract.SelectedCategory.Enum;
if (ModelState.IsValid)
{
selectedContractt.StartDate = contract.StartDate;
selectedContract.EndDate = contract.EndDate;
db.Contracts.Add(contract.creditContract);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(selectedContract);

Resources