I'm trying to save data from the view to the database from one main view and 1 partial view. Here AppRequest is the main class and the others are Purchase, PurchasingEmpl, PurchasingItems.
But when I debug the code, to the controller AppRequest main view data will pass but other class data not showing. Also not passing to the other tables also. Can you help me with this?
These are my model classes:
public class AppRequest
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Request Type")]
public int ReqType { get; set; }
[Required]
[Display(Name = "Requesting By")]
public int Req_By { get; set; }
[Required]
[Display(Name = "Requesting Date")]
public DateTime Req_Date { get; set; } = DateTime.Now;
[Required]
[Display(Name = "Request Location")]
public int Req_Location { get; set; }
[Required]
[Display(Name = "Request Heading")]
public string Req_Heading { get; set; }
[Display(Name = "Cover Note")]
public string Req_CoverNote { get; set; }
[Required]
[Display(Name = "Company Name")]
public int Company_Id { get; set; }
public bool Status { get; set; }
public int Create_By { get; set; }
public DateTime Created_Date { get; set; }
public int Modified_By { get; set; }
public DateTime Modified_Date { get; set; } = DateTime.Now;
public int Approval_Status { get; set; }
public virtual IList<Purchase> Purchase { get; set; }
[NotMapped]
public Purchase PurchaseItem { get; set; }
}
#region Purchase
public class Purchase
{
[Key]
public int Id { get; set; }
[Required]
[ForeignKey("AppRequest")]
public int Req_Id { get; set; }
public virtual AppRequest AppRequest { get; set; }
public virtual IList<PurchasingEmpl> PurchasingEmpl { get; set; }
public virtual IList<PurchasingItems> PurchasingItems { get; set; }
}
public class PurchasingEmpl
{
[Key]
public int Id { get; set; }
[Required]
[ForeignKey("Purchase")]
public int Purchase_Id { get; set; }
public virtual Purchase Purchase { get; set; }
public int Emp_Id { get; set; }
public bool Status { get; set; }
}
public class PurchasingItems
{
[Key]
public int Id { get; set; }
[Required]
[ForeignKey("Purchase")]
public int Purchase_Id { get; set; }
public virtual Purchase Purchase { get; set; }
public int Supp_Id { get; set; }
public int Itm_Description_Id { get; set; }
public decimal Unit_Amount { get; set; }
public byte[] Attachment { get; set; }
public decimal Qty { get; set; }
public string Recomandation { get; set; }
public bool Status { get; set; }
public bool Settled { get; set; } = false;
public string PoNo { get; set; }
}
This is the controller
public ActionResult Create(AppRequest appRequest)
{
if (ModelState.IsValid)
{
appRequest.Create_By = int.Parse(((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirst("UserId").Value);
appRequest.Created_Date = DateTime.Now;
appRequest.Modified_By= int.Parse(((System.Security.Claims.ClaimsIdentity)User.Identity).FindFirst("UserId").Value);
appRequest.Modified_Date = DateTime.Now;
appRequest.Status = true;
db.AppRequest.Add(appRequest);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(appRequest);
}
HTML View
````
#model Asp_PASMVC.Models.AppRequest
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
List<SelectListItem> ReqTypes = (List<SelectListItem>)TempData.Peek("RequestTyleList");
List<SelectListItem> Employees = (List<SelectListItem>)TempData.Peek("EmployeeList");
List<SelectListItem> Location = (List<SelectListItem>)TempData.Peek("LocationList");
List<SelectListItem> Companies = (List<SelectListItem>)TempData.Peek("ComapnyList");
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<!-- Default box -->
<div class="card">
<div class="card-header" >
<h3 class="card-title">Request Header Details</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" title="Collapse">
<i class="fas fa-minus"></i>
</button>
<button type="button" class="btn btn-tool" data-card-widget="remove" title="Remove">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<div class="card-body">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="row">
<div class="col-md-6 col-sm-6">
<div class="form-group row">
#Html.LabelFor(model => model.ReqType, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownListFor(model => model.ReqType, ReqTypes, new { #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.ReqType, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="form-group row">
#Html.LabelFor(model => model.Company_Id, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownListFor(model => model.Company_Id, Companies, new { #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.Company_Id, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="form-group row">
#Html.LabelFor(model => model.Req_By, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownListFor(model => model.Req_By, Employees, new { #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.Req_By, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="form-group row">
#Html.LabelFor(model => model.Req_Location, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownListFor(model => model.Req_Location, Location, new { #class = "js-dropdown" })
#Html.ValidationMessageFor(model => model.Req_Location, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group row">
#Html.LabelFor(model => model.Req_Heading, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-6">
#Html.EditorFor(model => model.Req_Heading, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Req_Heading, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6 col-sm-6">
<div class="form-group row">
#Html.LabelFor(model => model.Req_Date, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.EditorFor(model => model.Req_Date, new { htmlAttributes = new { #class = "js-datepicker" } })
#Html.ValidationMessageFor(model => model.Req_Date, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="form-group row">
#Html.LabelFor(model => model.Req_CoverNote, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-6">
#Html.EditorFor(model => model.Req_CoverNote, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Req_CoverNote, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
<!-- /.card-body -->
<!-- /.card-footer-->
</div>
<!-- /.card -->
</div>
</div>
</div>
</section>
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<!-- Default box -->
<div class="card">
<div class="card-header">
<h3 class="card-title">Request Main Details</h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" title="Collapse">
<i class="fas fa-minus"></i>
</button>
<button type="button" class="btn btn-tool" data-card-widget="remove" title="Remove">
<i class="fas fa-times"></i>
</button>
</div>
</div>
<div class="card-body">
#Html.Partial("_Purchase", Model.PurchaseItem);
<!-- /.card-body -->
<div class="card-footer">
<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>
<!-- /.card-footer-->
</div>
<!-- /.card -->
</div>
</div>
</div>
</section>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
````
Related
This question already has answers here:
Post an HTML Table to ADO.NET DataTable
(2 answers)
Closed 4 years ago.
I have this ViewModel:
public class DepositViewModel
{
public DepositViewModel()
{
DepositDate = DateTime.Now;
CollectedReceipts = new List<DepositQuantityAmountViewModel>();
CancelledReceipts = new List<DepositQuantityAmountViewModel>();
}
[Display(Name = "Deposit #")]
public long DepositId { get; set; }
[Display(Name = "Deposit Type")]
public string DepositType { get; set; }
[Display(Name = "Cashier #")]
public int CashierId { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Deposit Date")]
[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime DepositDate { get; set; }
[Display(Name = "Collected Receipts")]
public IList<DepositQuantityAmountViewModel> CollectedReceipts { get; set; }
[Display(Name= "Cancelled Receipts")]
public IList<DepositQuantityAmountViewModel> CancelledReceipts { get; set; }
[Display(Name = "Finance Reference")]
[MaxLength(2000)]
public string FinanceReference { get; set; }
[Display(Name = "Received Amount")]
[DisplayFormat(DataFormatString = "{0:N2}", ApplyFormatInEditMode = true)]
public decimal ReceivedAmount { get; set; }
[Display(Name = "Payment Modes")]
public IList<BDOs.PayMode> PaymentModes { get; set; }
}
public class DepositQuantityAmountViewModel
{
[Display(Name = "Description")]
public string Description { get; set; }
[Display(Name = "Category")]
public string Category { get; set; }
[Display(Name = "Count")]
public int Count { get; set; }
[Display(Name = "Total")]
[DisplayFormat(DataFormatString = "{0:N2}", ApplyFormatInEditMode = true)]
public decimal Amount { get; set; }
}
In my view, I have this setup:
<div class="row">
<div class="col-sm-2">
<div class="form-group">
<fieldset>
<legend>#Html.DisplayNameFor(m => m.PaymentModes)</legend>
<div class="col-sm-12">
<div class="row">
#foreach (var modelPaymentMode in Model.PaymentModes)
{
#Html.DisplayFor(m => modelPaymentMode, "_DepositPartPaymentModes")
}
</div>
</div>
</fieldset>
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<fieldset>
<legend>#Html.DisplayNameFor(m => m.CollectedReceipts)</legend>
#Html.DisplayFor(m => m.CollectedReceipts, "_DepositPartDetail")
</fieldset>
</div>
</div>
<div class="col-sm-5">
<div class="form-group">
<fieldset>
<legend>#Html.DisplayNameFor(m => m.CancelledReceipts)</legend>
#Html.DisplayFor(m => m.CancelledReceipts, "_DepositPartDetail")
</fieldset>
</div>
</div>
</div>
And here are the display templates:
_DepositPartPaymentModes.cshtml
#model DA.Services.IBS.Business.BDO.PayMode
<div class="form-group">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control", #readonly = "readonly" })
</div>
_DepositPartDetail.cshtml
#model IEnumerable<DA.Services.IBS.Web.FinancePortalFull.Models.DepositQuantityAmountViewModel>
#foreach (var countAmountPair in Model)
{
if (countAmountPair.Category == "TotalCollected" || countAmountPair.Category == "TotalCancelled")
{
<div class="col-sm-12">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => countAmountPair.Description, new { #class = "form-control", #readonly = "readonly" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => countAmountPair.Amount, "{0:N2}", new { #class = "form-control", type = "numeric", dir = "rtl", #readonly = "readonly" })
</div>
</div>
</div>
</div>
}
else
{
<div class="col-sm-12">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => countAmountPair.Count, "{0:N0}", new { #class = "form-control", type = "numeric", dir = "rtl", #readonly = "readonly" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => countAmountPair.Amount, "{0:N2}", new { #class = "form-control", type = "numeric", dir = "rtl", #readonly = "readonly" })
</div>
</div>
</div>
</div>
}
}
I have tried to bind each template separately looking at different guides. I cannot get the collections to be returned to postback as they are null. They display properly all three collections are null on submission.
What am I doing wrong?
Solution
Do not use ForEach Loops in views to iterate collections. Use For Loops.
The issue is in using foreach loops. When this is rendered in HTML, the input elements are not given names that will mean anything to the model binder when you post. You need to change these to for loops and the inputs will be rendered correctly.
You may also need to change your model so that the list is not null when the binder is trying to add to it.
Eg:
#for (int i = 0; i < Model.PaymentModes; i++)
{
#Html.DisplayFor(m => Model.PaymentModes[i], "_DepositPartPaymentModes")
}
Use for loop instead of foreach.
Element should be like this.
<input type="text" name="List[0].PropertyName" value="XYZ" />
change #model IEnumerable<DA.Services.IBS.Web.FinancePortalFull.Models.DepositQuantityAmountViewModel> to #model List<DA.Services.IBS.Web.FinancePortalFull.Models.DepositQuantityAmountViewModel>
_DepositPartDetail.cshtml
for (int i=0;i<Model.Count(); i++)
{
{
if (countAmountPair.Category == "TotalCollected" || countAmountPair.Category == "TotalCancelled")
{
<div class="col-sm-12">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => m[i].Description, new { #class = "form-control", #readonly = "readonly" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => m[i].Amount, "{0:N2}", new { #class = "form-control", type = "numeric", dir = "rtl", #readonly = "readonly" })
</div>
</div>
</div>
</div>
}
else
{
<div class="col-sm-12">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => m[i].Count, "{0:N0}", new { #class = "form-control", type = "numeric", dir = "rtl", #readonly = "readonly" })
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.TextBoxFor(m => m[i].Amount, "{0:N2}", new { #class = "form-control", type = "numeric", dir = "rtl", #readonly = "readonly" })
</div>
</div>
</div>
</div>
}
}
I'm using ASP.NET c# mvc with entity framework to build a web site. So I want to create user profile for the registered user which is editable. Within that i have coded for a image upload part and it was not successfully worked out for me.
This is my View file (Manage.cshtml)
#model TheFoody.Models.ManageViewModel
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script>
function editFunc() {
document.getElementById("Photo").disabled = false;
document.getElementById("FirstName").disabled = false;
document.getElementById("LastName").disabled = false;
document.getElementById("Email").disabled = false;
document.getElementById("UserType").disabled = false;
document.getElementById("Address").disabled = false;
document.getElementById("City").disabled = false;
document.getElementById("District").disabled = false;
document.getElementById("Phone").disabled = false;
//document.getElementById("Photo").disabled = false;
document.getElementById("PostCode").disabled = false;
document.getElementById("Status").disabled = false;
}
function reload() {
window.location.href = "http://localhost:1672/Manage";
}
</script>
<div class="breadcrumb-wrapper">
<div class="container">
<ol class="breadcrumb-list booking-step">
<li>Home</li>
<li><span>User Profile</span></li>
</ol>
</div>
</div>
<div class="admin-container-wrapper">
<div class="container">
<div class="GridLex-gap-15-wrappper">
<div class="GridLex-grid-noGutter-equalHeight">
<div class="GridLex-col-3_sm-4_xs-12">
<div class="admin-sidebar">
<div class="admin-user-item">
<div class="image">
<img src="http://localhost:33409/images/man/01.jpg" alt="image" class="img-circle" />
</div>
<h4>John Doe</h4>
<p class="user-role">Foodies</p>
</div>
<div class="admin-user-action text-center">
Edit
Deactivate
</div>
<ul class="admin-user-menu clearfix">
<li>
<i class="fa fa-tachometer"></i> Dashboard
</li>
<li class="active">
<i class="fa fa-user"></i> Profile
</li>
<li>
<i class="fa fa-key"></i> Change Password
</li>
<li>
<i class="fa fa-bookmark"></i> Favourite Restaurant
</li>
<li>
<i class="fa fa-sign-out"></i> Logout
</li>
</ul>
</div>
</div>
<div class="GridLex-col-9_sm-8_xs-12">
<div class="admin-content-wrapper">
<div class="admin-section-title">
<h2>Profile</h2>
<p>Enquire explain another he in brandon enjoyed be service.</p>
</div>
<!--<form class="post-form-wrapper" action="http://localhost:33409/UpdateProfile/Edit" id="updateForm" method="POST">-->
#using (Html.BeginForm("Manage", "Manage", new { #id = "updateForm", #class = "post-form-wrapper" }, FormMethod.Post))
{
#Html.AntiForgeryToken();
<div class="row gap-20">
<div class="col-sm-6 col-md-4">
#ViewBag.Error
<div class="form-group bootstrap-fileinput-style-01">
<label>Photo</label>
<input type="file" name="Photo" id="Photo" disabled>
#*#Html.HiddenFor(model => model.Photo, new { #class = "form-control", disabled = "disabled" })*#
#*<input type="hidden" value="default" id="photo" name="photo" />*#
<span class="font12 font-italic">** photo must not bigger than 250kb</span>
</div>
</div>
<div class="clear"></div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>First Name</label>
#Html.TextBoxFor(model => model.FirstName, new { #class = "form-control", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>Last Name</label>
#Html.TextBoxFor(model => model.LastName, new { #class = "form-control", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>Email</label>
#*<input type="email" class="form-control" value=Session["UserEmail"].tostring() id="email" name="email" disabled>*#
#Html.TextBoxFor(model => model.Email, new { #class = "form-control", disabled = "disabled"})
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="clear"></div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>Address</label>
#*<input type="text" class="form-control" value="254" id="address" name="address" disabled>*#
#Html.TextBoxFor(model => model.Address, new { #class = "form-control", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="clear"></div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>District</label>
#*<input type="text" class="form-control" value="254" id="district" name="district" disabled>*#
#Html.TextBoxFor(model => model.District, new { #class = "form-control", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.District, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>City/town</label>
#*<input type="text" class="form-control" value="Somewhere " id="city" name="city" disabled>*#
#Html.TextBoxFor(model => model.City, new { #class = "form-control", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>PostCode</label>
#*<input type="text" class="form-control" value="Somewhere " id="postcode" name="postcode" disabled>*#
#Html.TextBoxFor(model => model.PostCode, new { #class = "form-control", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.PostCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>UserType</label>
</div>
<div class="col-sm-6 col-md-4">
#{
List<SelectListItem> listItemsUserType = new List<SelectListItem>();
listItemsUserType.Add(new SelectListItem
{
Text = "Admin",
Value = "Admin"
});
listItemsUserType.Add(new SelectListItem
{
Text = "Customer",
Value = "Customer",
Selected = true
});
listItemsUserType.Add(new SelectListItem
{
Text = "Business",
Value = "Business"
});
}
#Html.DropDownListFor(model => model.UserType, listItemsUserType, "-- Select Status --", new { #class = "form-control",disabled = "disabled" })
</div>
</div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>Status</label>
</div>
<div class="col-sm-6 col-md-4">
#{
List<SelectListItem> listItemsStatus = new List<SelectListItem>();
listItemsStatus.Add(new SelectListItem
{
Text = "Availble",
Value = "Available",
Selected = true
});
listItemsStatus.Add(new SelectListItem
{
Text = "Not Available",
Value = "Not Available"
});
}
#Html.DropDownListFor(model => model.Status, listItemsStatus, "-- Select Status --", new { #class = "form-control",disabled = "disabled" })
</div>
</div>
<div class="clear"></div>
<div class="col-sm-6 col-md-4">
<div class="form-group">
<label>Phone Number</label>
#*<input type="text" class="form-control" value="+66-85-221-5489" id="phone" name="phone" disabled>*#
#Html.TextBoxFor(model => model.Phone, new { #class = "form-control", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="clear"></div>
<div class="col-sm-12 mt-10">
#*<input type="submit" onclick="document.getElementById('updateform').submit()" class="btn btn-primary" value="Save" />*#
<input type="submit" class="btn btn-primary" value="Save" />
Cancel
</div>
</div>
}
<!--</form>-->
</div>
</div>
</div>
</div>
</div>
</div>
And it will give a UI like below.
And my Model file is like below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace TheFoody.Models
{
public class ManageViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Photo { get; set; }
public string Address { get; set; }
public string City { get; set; }
public int PostCode { get; set; }
public string District { get; set; }
public string UserType { get; set; }
public string Status { get; set; }
}
}
And my Controller looks like this (ManageController.cs)
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TheFoody.DataAccess;
using TheFoody.Models;
namespace TheFoody.Controllers
{
public class ManageController : Controller
{
//ManageContext db = new ManageContext();
//
//GET: /Manage/
public ActionResult Manage()
{
//LoadData();
var manageviewmodel = new ManageViewModel() { Email = Session["UserEmail"].ToString() };
return View(manageviewmodel);
}
private bool isValidContentType(string contentType)
{
return contentType.Equals("Images/png") || contentType.Equals("Images/gif") || contentType.Equals("Images/jpg") || contentType.Equals("Images/jpeg");
}
private bool isValidContentLength(int contentLength)
{
return (contentLength / 1024) / 1024 < 1; //1MB
}
[HttpPost]
public ActionResult Manage(ManageViewModel manageviewmodel, HttpPostedFileBase Photo)
{
TheFoodyContext db = new TheFoodyContext();
User user_to_update = db.Users.SingleOrDefault(s => s.email == manageviewmodel.Email);
if (ModelState.IsValid)
{
try
{
if (!isValidContentType(Photo.ContentType))
{
ViewBag.Error = "Only JPG , JPEG , GIF & PNG are allowed!";
return View("Manage");
}
else if (!isValidContentLength(Photo.ContentLength))
{
ViewBag.Error = "Your File is too Large!";
return View("Manage");
}
else
{
if (user_to_update != null && (Photo != null && Photo.ContentLength > 0))
{
var fileName = Path.GetFileName(Photo.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
Photo.SaveAs(path);
user_to_update.email = manageviewmodel.Email;
user_to_update.fname = manageviewmodel.FirstName;
user_to_update.lname = manageviewmodel.LastName;
user_to_update.phone = manageviewmodel.Phone;
//user_to_update.photo = manageviewmodel.Photo;
user_to_update.address = manageviewmodel.Address;
user_to_update.city = manageviewmodel.City;
user_to_update.postcode = manageviewmodel.PostCode;
user_to_update.district = manageviewmodel.District;
user_to_update.user_type = manageviewmodel.UserType;
user_to_update.status = manageviewmodel.Status;
db.SaveChanges();
return RedirectToAction("Manage");
}
}
}
catch (Exception ex)
{
return View("Error");
}
return View(manageviewmodel);
}
return View(manageviewmodel);
}
}
}
And the design of My database is;
And my DbContext file looks as below;
namespace TheFoody.DataAccess
{
using System;
using System.Collections.Generic;
public partial class User
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public User()
{
this.Restaurants = new HashSet<Restaurant>();
}
public string email { get; set; }
public string password { get; set; }
public string fname { get; set; }
public string lname { get; set; }
public string phone { get; set; }
public string photo { get; set; }
public string address { get; set; }
public string city { get; set; }
public Nullable<decimal> postcode { get; set; }
public string district { get; set; }
public string user_type { get; set; }
public string status { get; set; }
public System.DateTime created_date { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Restaurant> Restaurants { get; set; }
}
}
But when i'm executing all these things My ~/Content/Images file does not have the image file that i have uploaded. And it will give me the error to the view as follows.
Actually I wanted to save the path to the relevant image file in the database and image in the ~/Content/Images folder which in following hierarchy.
I'm very new to this environment specially Entity Framework. So i don't know how to correct my code to get what i'm expected.
First you have to do is copy and past that image to your image folder
System.IO.File.Copy("source", "destination");
Then save that path to your data base.
How to save data from Select box in Entity Framework Database relation Many to Many
There are two classes one weapon and other User..
public class Weapon { } public class User { }
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
public class Wepon
{ public int ID { get; set; }
public string Wepon_Name { get; set; }
public int Power { get; set; }
}
Which should have relation Many to Many Using FormCollection and Model
User Class
And Weapon Class
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
**public List<Wepon> WeposInList { get; set; }**
}
public class Wepon
{
public int ID { get; set; }
public string Wepon_Name { get; set; }
public int Power { get; set; }
public List<User> UsersHaveWeponsList { get; set; }// User the List for M to M
}
DBContext
public class DbContexFor : DbContext
{
public DbContexFor()
: base("name=ConnectionStringName")
{
}
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Wepon> Wepons { get; set; }
}
}
**
The Controller Code
**
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Name,Type")] User user, FormCollection formData)
{
if (ModelState.IsValid)
{
var ss = formData["ShipFromCountries"].ToString();
user.WeposInList = db.Wepons.Where(c => c.Wepon_Name == ss).ToList();
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
And the Html Code
#model enumVarAction.Models.User
#{
var list = ViewBag.MyList;
ViewBag.Title = "Create";
}
Create Html Page
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User</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.Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Type, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Type, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.WeposInList, htmlAttributes: new { #class = "control-label col-md-2" })
<select id="ShipFromCountries" multiple="multiple" name="ShipFromCountries">
<div class="col-md-10">
#foreach (var VARIABLE in list)
{
<option value="#VARIABLE.Wepon_Name">#VARIABLE.Wepon_Name</option>
}
</div>
</select>
</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")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
**
Debug at Controller
**
**
Data is Database
**
I have an MVC5 project with Entity 6 framework and I am having trouble getting the correct information passed to the edit action on the post, in order to bind it to the models. The ModelState of my viewModel comes back as invalid. I am not sure what I am missing. I am guessing that it has to do with the way that my Editor templates are setup vs the structure of my models but I need some help figuring it out. I have spent many hours changing things to try and get this working and I still cant get it corrected.
My ViewModel:
namespace CommunityHealth.Models.ViewModels
{
public class ActivityViewModel
{
public virtual IList<JunctionTypeAction> junctionTypeActions{ get; set; }
public virtual IList<JunctionDepartmentAction> junctionDepartmentActions{ get; set; }
public virtual IList<JunctionPopulationAction> junctionPopulationActions { get; set; }
public virtual CommunityAction Action { get; set; }
}
}
The Community Action Model:
public partial class CommunityAction
{
public CommunityAction()
{
this.JunctionPopulationActions = new HashSet<JunctionPopulationAction>();
this.JunctionDepartmentActions = new HashSet<JunctionDepartmentAction>();
this.JunctionTypeActions = new HashSet<JunctionTypeAction>();
}
public int ActionID { get; set; }
public System.DateTime StartDate { get; set; }
public Nullable<System.DateTime> EndDate { get; set; }
public string BreifDescription { get; set; }
public Nullable<int> Duration { get; set; }
public int LocationID { get; set; }
public string SubLocation { get; set; }
public int ProgramID { get; set; }
public string Notes { get; set; }
public string AddedBy { get; set; }
public byte[] RecordVersion { get; set; }
public virtual Location Location { get; set; }
public virtual Program Program { get; set; }
public virtual ICollection<JunctionPopulationAction> JunctionPopulationActions { get; set; }
public virtual ICollection<JunctionDepartmentAction> JunctionDepartmentActions { get; set; }
public virtual ICollection<JunctionTypeAction> JunctionTypeActions { get; set; }
}
The Models for the Junction Tables:
JunctionDepartmentAction:
public partial class JunctionDepartmentAction
{
public int IndexID { get; set; }
public int DepartmentID { get; set; }
public int ActionID { get; set; }
public string SubDepartment { get; set; }
public int Individuals { get; set; }
public virtual CommunityAction CommunityAction { get; set; }
public virtual Department Department { get; set; }
}
JunctionPopulationAction:
public partial class JunctionPopulationAction
{
public int IndexID { get; set; }
public int PopulationID { get; set; }
public int ActionID { get; set; }
public bool isActive { get; set; }
public virtual CommunityAction CommunityAction { get; set; }
public virtual TargetPopulation TargetPopulation { get; set; }
}
JunctionTypeAction:
public partial class JunctionTypeAction
{
public int IndexID { get; set; }
public int TypeID { get; set; }
public int ActionID { get; set; }
public virtual ActivityType ActivityType { get; set; }
public virtual CommunityAction CommunityAction { get; set; }
}
Event Controller Edit Action Methods:
// GET: /Event/Edit/5
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
CommunityAction communityaction = await db.CommunityActions.FindAsync(id);
ActivityViewModel activityviewmodel = new ActivityViewModel();
activityviewmodel.Action = communityaction;
IList<JunctionTypeAction> junctiontypeactions = await db.JunctionTypeActions.Where(d => d.ActionID == communityaction.ActionID).ToListAsync();
IList<JunctionDepartmentAction> junctiondepartmentactions = await db.JunctionDepartmentActions.Where(d => d.ActionID == communityaction.ActionID).ToListAsync();
IList<JunctionPopulationAction> junctionpopulationactions = await db.JunctionPopulationActions.Where(d => d.ActionID == communityaction.ActionID).ToListAsync();
activityviewmodel.junctionTypeActions = junctiontypeactions.ToList();
activityviewmodel.junctionDepartmentActions = junctiondepartmentactions.ToList();
activityviewmodel.junctionPopulationActions = junctionpopulationactions.ToList();
if (communityaction == null)
{
return HttpNotFound();
}
ViewBag.LocationID = new SelectList(db.Locations, "LocationID", "LocationName", activityviewmodel.Action.LocationID);
ViewBag.ProgramID = new SelectList(db.Programs, "ProgramID", "ProgramID", activityviewmodel.Action.ProgramID);
return View(activityviewmodel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(ActivityViewModel activity)
{
//request added for debugging purposes
Request.ToString();
if (ModelState.IsValid)
{
db.Entry(activity).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.LocationID = new SelectList(db.Locations, "LocationID", "LocationName", activity.Action.LocationID);
ViewBag.ProgramID = new SelectList(db.Programs, "ProgramID", "ProgramID", activity.Action.ProgramID);
return View(activity);
}
And finally my Views. I am using three editor templates for the junction tables in the DataBase and one more for the CommunityAction object. I then have a view for the event that uses the three editor templates to display the parts of the ViewModel.
CommunityAction.cshtml:
#model CommunityHealth.Models.CommunityAction
<div class="form-horizontal">
<h4>CommunityAction</h4>
<hr />
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.ActionID)
#Html.HiddenFor(model => model.RecordVersion)
<div class="form-group">
#Html.LabelFor(model => model.StartDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StartDate)
#Html.ValidationMessageFor(model => model.StartDate)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EndDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EndDate)
#Html.ValidationMessageFor(model => model.EndDate)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BreifDescription, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BreifDescription)
#Html.ValidationMessageFor(model => model.BreifDescription)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Duration, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Duration)
#Html.ValidationMessageFor(model => model.Duration)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LocationID, "Location", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Location, ViewBag.LocationID as SelectList, new { htmlAttributes = new { #class = "control-form" } })
#Html.ValidationMessageFor(model => model.Location)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SubLocation, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SubLocation)
#Html.ValidationMessageFor(model => model.SubLocation)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProgramID, "Program", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ProgramID, ViewBag.ProgramID as SelectList, new { htmlAttributes = new { #class = "control-form" } })
#Html.ValidationMessageFor(model => model.Program)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Notes, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Notes)
#Html.ValidationMessageFor(model => model.Notes)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AddedBy, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AddedBy)
#Html.ValidationMessageFor(model => model.AddedBy)
</div>
</div>
<div class="form-group">
<div class="col-md-10">
</div>
</div>
</div>
JunctionTypeAction.cshtml:
#model CommunityHealth.Models.JunctionTypeAction
<div class="type">
<fieldset>
#Html.HiddenFor(model => model.ActionID)
#Html.HiddenFor(model => model.IndexID)
#Html.EditorFor(model => model.TypeID, "TypeName", new { #class = "control-label col-md-2" })
</fieldset>
</div>
JunctionDepartmentAction.cshtml:
#model CommunityHealth.Models.JunctionDepartmentAction
#using CommunityHealth.Models
<div>
<table>
<tbody>
<tr>
<td>
#Html.HiddenFor(model => model.ActionID)
#Html.HiddenFor(model => model.IndexID)
#Html.EditorFor(model => model.DepartmentID, "DepartmentName", new { #class = "control-label col-md-2" })
</td>
<td>
#Html.EditorFor(model => model.SubDepartment, "SubDepartment", new { #class = "control-label col-md-2 " })
</td>
<td>
#Html.EditorFor(model => model.Individuals)
</td>
</tr>
</tbody>
</table>
</div>
JunctionPopulationAction.cshtml:
#model CommunityHealth.Models.JunctionPopulationAction
<div class="population">
<fieldset>
#Html.HiddenFor(model => model.ActionID)
#Html.HiddenFor(model => model.IndexID)
#Html.EditorFor(model => model.PopulationID, "PopulationName", new { #class = "control-label col-md-2" })
</fieldset>
</div>
Views\Event\Edit.cshtml:
#model CommunityHealth.Models.ViewModels.ActivityViewModel
#using CommunityHealth.Models.ViewModels;
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm("Edit","Event",FormMethod.Post))
{
#Html.AntiForgeryToken()
<div>
<div class="form-group">
#Html.EditorFor(model => model.Action)
</div>
<div class="form-group">
#Html.Label("Types")
<div class="col-md-10">
<fieldset>
#for (int x = 0; x < Model.junctionTypeActions.Count(); x++)
{
#Html.EditorFor(model => model.junctionTypeActions[x])
}
</fieldset>
</div>
</div>
<div class="form-group">
#Html.Label("Departments")
<div class="col-md-10">
#for (int x = 0; x < Model.junctionDepartmentActions.Count(); x++)
{
#Html.EditorFor(model => model.junctionDepartmentActions[x])
}
</div>
</div>
<div class="form-group">
#Html.Label("Target Populations")
<div class="col-md-10">
#for (int x = 0; x < Model.junctionDepartmentActions.Count(); x++)
{
#Html.EditorFor(model => model.junctionPopulationActions[x])
}
</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>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I am getting this error when I examine the request:
"The parameter conversion from type 'System.String' to type 'CommunityHealth.Models.CommunityAction' failed because no type converter can convert between these types."
The reason for that error is because you model has a property named activity (typeof CommunityAction), and the parameter of your post method is also named activity. Change the parameter name to anything other than the name of a property in the model(s)
public async Task<ActionResult> Edit(ActivityViewModel model)
{
....
}
Side notes
Simply use #Html.EditorFor(m => m.junctionTypeActions) to generate
the html for collections (not in a for loop). #Html.EditorFor()
is smart enough to recognize collections and generate the correct
html.
Generating all those hidden inputs is bad practice and degrades
performance (and any malicious user could change the values anyway).
Use view models for each or your types that contain only the
properties you need to display/edit.
I'm in VS 2013 and am completely new to ASP.NET MVC in general. I have been attempting to do this for sometime with no luck. Have a user complete a form with an image upload, and have that form with the image written to the DB. I know its best to write the path to the DB and store the image in the content folder of the application but I have no idea how to do any of this. Can someone give me a starting point?
I also have a ClientUtility.cs that is used to populate drop-downs but I don't see this being needed right now.
Currently the data type for the image ref in the db is VARCHAR(255).
Controller:
private TpsEntities db = new TpsEntities();
[HttpPost]
public ActionResult SaveStaffDetails(RegisterStaffViewModel model)
{
var staff = new staffTable()
{
staffFirstName = model.FirstName,
staffLastName = model.LastName,
staffTitle = model.SelectedTitle,
staffAddress = model.Address,
staffCity = model.City,
staffState = model.SelectedState,
staffZip = model.ZipCode,
staffExperience = model.SelectedExperience,
staffEducation = model.SelectedEducation,
desiredSalary = model.SelectedSalary,
staffProfession = model.SelectedProfession,
staffAvailibity = model.SelectedAvailability,
staffEmail = model.EmailAddress,
staffPhoneNum = model.PhoneNumber,
staffPhoto = null,
userID = model.UserId
};
using (var db = new TpsEntities())
{
db.staffTables.Add(staff);
db.SaveChanges();
}
var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = userManager.FindById(model.UserId);
userManager.AddToRole(model.UserId, "Staff");
ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim(ClaimTypes.Role, "Staff"));
var AuthenticationManager = System.Web.HttpContext.Current.GetOwinContext().Authentication;
AuthenticationManager.SignIn(new AuthenticationProperties() {IsPersistent = false}, identity);
return RedirectToAction("Index", "Home");
}
}
ViewModel:
public class RegisterStaffViewModel
{
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[Display(Name = "Address")]
public string Address { get; set; }
public System.Web.UI.WebControls.ListItemCollection Title { get; set; }
[Required]
[Display(Name = "Title")]
public string SelectedTitle { get; set; }
[Required]
[Display(Name = "City")]
public string City { get; set; }
public System.Web.UI.WebControls.ListItemCollection States { get; set; }
[Required]
[Display(Name = "State")]
public string SelectedState { get; set; }
[Required]
[Display(Name = "Zip Code")]
public double? ZipCode { get; set; }
[Required]
[Phone]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email Address")]
public string EmailAddress { get; set; }
public System.Web.UI.WebControls.ListItemCollection Experience { get; set; }
[Required]
[Display(Name = "Experience")]
public string SelectedExperience { get; set; }
public System.Web.UI.WebControls.ListItemCollection Education { get; set; }
[Required]
[Display(Name = "Education")]
public string SelectedEducation { get; set; }
public System.Web.UI.WebControls.ListItemCollection Salary { get; set; }
[Required]
[Display(Name = "Salary")]
public string SelectedSalary { get; set; }
public System.Web.UI.WebControls.ListItemCollection Profession { get; set; }
[Required]
[Display(Name = "Profession")]
public string SelectedProfession { get; set; }
public System.Web.UI.WebControls.ListItemCollection Availability { get; set; }
[Required]
[Display(Name = "Availability")]
public string SelectedAvailability { get; set; }
public string UserId { get; set; }
}
View:
#*Start of Registration Form for Staff*#
#using (Html.BeginForm("SaveStaffDetails", "Staff", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.UserId)
<fieldset>
<!-- Form Name -->
<legend>Register New Staff</legend>
#*First Name*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.FirstName, new { #class = "form-control input-md", #placeholder = "First Name" })
</div>
</div>
#*Last Name*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.LastName, new { #class = "form-control input-md", #placeholder = "Last Name" })
</div>
</div>
#*Person Title*#
<div class="form-group">
<label class="col-md-6 control-label" for="title">Title</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedTitle, new SelectList(Model.Title, "Text", "Value"))
</div>
</div>
#*Address Line*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.Address, new { #class = "form-control input-md", #placeholder = "Address" })
</div>
</div>
#*City*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.City, new { #class = "form-control input-md", #placeholder = "City" })
</div>
</div>
#*State*#
<div class="form-group">
<label class="col-md-6 control-label" for="state">State</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedState, new SelectList(Model.States, "Text", "Value"))
</div>
</div>
#*Zip Code*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.ZipCode, new { #class = "form-control input-md", #placeholder = "Zip Code" })
</div>
</div>
#*Phone Number*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.PhoneNumber, new { #class = "form-control input-md", #placeholder = "Phone Number" })
</div>
</div>
#*Email Address*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.EmailAddress, new { #class = "form-control input-md", #placeholder = "Email Address" })
</div>
</div>
#*Experience*#
<div class="form-group">
<label class="col-md-6 control-label" for="experience">Experience</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedExperience, new SelectList(Model.Experience, "Text", "Value"))
</div>
</div>
#*Education*#
<div class="form-group">
<label class="col-md-6 control-label" for="education">Education</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedEducation, new SelectList(Model.Education, "Text", "Value"))
</div>
</div>
#*Desired Salary*#
<div class="form-group">
<label class="col-md-6 control-label" for="salary">Desired Salary</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedSalary, new SelectList(Model.Salary, "Text", "Value"))
</div>
</div>
#*Profession*#
<div class="form-group">
<label class="col-md-6 control-label" for="profession">Profession</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedProfession, new SelectList(Model.Profession, "Text", "Value"))
</div>
</div>
#*Availability*#
<div class="form-group">
<label class="col-md-6 control-label" for="availability">Availability</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedAvailability, new SelectList(Model.Availability, "Text", "Value"))
</div>
</div>
<!-- INSERT IMAGE UPLOAD HERE -->
</fieldset>
<input type="submit" value="Save" />
}
Edit your controller as the following code.I assumed that staffPhoto is taking picturepath.
public ActionResult SaveStaffDetails(RegisterStaffViewModel model,HttpPostedFileBase image)
{
if (Request.Files.Count > 0) {
string FileName = Guid.NewGuid().ToString().Replace("-", "");
string Path = System.IO.Path.GetExtension(Request.Files[0].FileName);
string FullPath = "~/Images/StaffPhotos/" + FileName + Path;
Request.Files[0].SaveAs(Server.MapPath(FullPath));
staffPhoto = FileName + Path;
}
}
In your view you need a file post input
<input type="file" class="filestyle" name="image" data-classbutton="btn btn-primary" data-input="false">