The problem is when i want to edit a song in my project which has 4 genres and let's say i want to remove 1 and save, it drops an exception. My idea was to tell the controller to remove the 4 i had on the song and add the 3 which i chose. But that would mean removing from the local database and adding the new ones, i just have no idea how to do it. Any help is appreciated.
I made a pivot DataTable which contains song and genre ID's and which is conected to 2 other DataTables, where one has the genre types and the other song information. The listBoxFor in the view shows which genres are in the song, but when i delete one it doesn't save. I think the change needs to happen within the HttpPost of the Edit controller.
I am still new to coding and programming so I apologize if my question isn't too precise. If any more information is needed please tell me.
This is the Controller:
using (ApplicationDbContext db = new ApplicationDbContext())
{
var song = db.Songs.Find(model.SongId);
int[] genreIds = db.SongsGenres.Where(x => x.SongId == song.Id).Select(x=> x.GenreId).ToArray();
song.Performer = model.Performer;
song.Title = model.Title;
//song.Id = model.GenreIds;
song.Year = model.Year;
song.YoutubeLink = model.YoutubeLink;
db.Entry(song).State = EntityState.Modified;
foreach (var genreId in model.GenreIds)
{
// tu treba ici if petlja koja izbriše stari zapis iz baze
// i stavi novi editirani
db.SongsGenres.Add(new SongsGenre
{
Song = song,
//SongId = song.Id,
GenreId = genreId
});
}
db.SaveChanges();
return RedirectToAction("List");
}
}
}
}
This is the HTML(view):
#using System.Web.UI.WebControls
#model MusicBox.Models.EditViewModel
#{
ViewBag.Title = "Edit";
}
<h2>Editiraj pjesmu</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label class="control-label col-md-2" for="Performer">Izvođač</label>
<div class="col-md-10">
#Html.EditorFor(model => model.Performer, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.Performer, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="Title">Pjesma</label>
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="Year">Godina</label>
<div class="col-md-10">
#Html.EditorFor(model => model.Year, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.Year, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="YoutubeLink">Youtube link</label>
<div class="col-md-10">
#Html.EditorFor(model => model.YoutubeLink, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.YoutubeLink, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="Genre">Žanr</label>
<div class="col-md-10">
#Html.ListBoxFor(model => model.GenreIds, new SelectList(Model.Genres, "Value", "Text"), htmlAttributes: new { #class = "form-control select2", required = "required", multiple = "multiple" })
#*#Html.EditorFor(model => model.GenreIds, new {htmlAttributes = new {#class = "form-control"}})*#
#Html.ValidationMessageFor(model => model.GenreIds, "", new { #class = "text-danger" })
</div>
</div>
#Html.HiddenFor(model => model.SongId)
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Spremi" class="btn btn-primary" />
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
#Html.ActionLink("Back to List", "List")
</div>
</div>
}
#section scripts
{
<script type="text/javascript">
$(".select2").select2({
val: '#Html.Raw(Json.Encode(Model.GenreIds))'
});
</script>
}
EDITED.
Related
I add a studid referance in another table
when I store the studid then give the error There is no ViewData item of type 'IEnumerable' that has the key studid'
HomeController.cs
private readonly dbstuudEntities dbstud;
public HomeController()
{
dbstud = new dbstuudEntities();
}
public ActionResult BlogCreate()
{
return View();
}
[HttpPost]
public ActionResult BlogCreate(blog blg)
{
ViewBag.studid = new SelectList(dbstud.students, "studid");
dbstud.blogs.Add(blg);
dbstud.SaveChanges();
}
BlogCreate.cshtml
#model DemoFFI.Models.blog
#{
ViewBag.Title = "BlogCreate";
}
<h2>BlogCreate</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>blog</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#*<div class="form-group">
#Html.LabelFor(model => model.blogid, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.blogid, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.blogid, "", new { #class = "text-danger" })
</div>
</div>*#
<div class="form-group">
#Html.LabelFor(model => model.blogdescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.blogdescription, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.blogdescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.blogtype, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(x => x.blogtype, new List<SelectListItem>
{
new SelectListItem() {Text = "public", Value="public"},
new SelectListItem() {Text = "private", Value="private"},
})
#*#Html.EditorFor(model => model.blogtype, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.ValidationMessageFor(model => model.blogtype, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.studid, "studid", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
//here get an error There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key studid'
#Html.DropDownListFor(model => model.studid, ViewBag.studid as IEnumerable<SelectListItem>)
#Html.ValidationMessageFor(model => model.studid, "", 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>
}
I add a studid referance in another table but it store the null
//here get an error There is no ViewData item of type 'IEnumerable' that has the key studid'
#Html.DropDownListFor(model => model.studid, ViewBag.studid as IEnumerable<SelectListItem>)
I have an edit form page on my website that allows users to edit quantities, on this page I used editorFor's which look like this
#Html.EditorFor(model => model.item_qty, new { htmlAttributes = new { min = 0, #class = "form-control" } })
And I have a submit button that looks like this
<input type="submit" value="Save" class="btn" />
I want to make it so that if the user increases the qty, it will go ahead and run the post method. But on the other hand, if a user was to decrease the qty, I would want the save button to look like this
<input type="submit" value="Save" onclick="confirm()" class="btn" />
Where it gets the user to confirm before running the post.
How can I make my save button change based on what the user types into the editorFor?
Here is my entire view page as requested
#model PIC_Program_1._0.Models.JODetails
#using PIC_Program_1._0.Models
#{
ViewBag.Title = "Edit";
PIC_Program_1_0Context db = new PIC_Program_1_0Context();
var currentData = db.JODetails.AsNoTracking().FirstOrDefault(j => j.ID == Model.ID);
Component comp = db.Components.Find(Model.ComponentID);
Item i = db.Items.Find(Model.ItemID);
}
<script type="text/javascript">
function clicked(e) {
if(#i != null ) {
var itemDiff = // model - new editorfor value;
if (!confirm('Are you sure? Doing this will reduce item ' + #i.ItemID + ' future stock to ' + itemDiff))e.preventDefault();
}
}
function OnChangeEvent(){
alert("value is changed");
var itemQty = $('#itemQTY').val();
if (itemQty < #Model.item_qty) {
btn.Attributes.Add("onclick", "clicked(event)");
}
}
</script>
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>JODetails</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
#Html.HiddenFor(model => model.subDetail)
<p style="color:red">#ViewBag.Error</p>
<div class="form-group">
#Html.LabelFor(model => model.ItemID, "ItemID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ItemID", null, "-- Select --", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ItemID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.item_qty, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#if (ViewBag.isValid == false)
{
#Html.TextBoxFor(model => model.item_qty, new { disabled = "disabled", #Value = Model.item_qty, #readonly = "readonly" })
}
else
{
#Html.EditorFor(model => model.item_qty, new { htmlAttributes = new { onchange = "OnChangeEvent()", min = 0, #class = "form-control" #id = "itemQTY"} })
#Html.ValidationMessageFor(model => model.item_qty, "", 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"/>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
For the on change you can on your editor for:
#Html.EditorFor(model => model.item_qty, new { htmlAttributes = new { onchange = "OnChangeEvent(this)", min = 0, #class = "form-control", #id ="someId" } })
<script type="text/javascript">
function OnChangeEvent(){
var itemQty = $('#someID').val(); //This will give you value of editor for
alert("new value is: " + itemQty);
//Call some controller function here and do your increase/decrease logic and return value so we know what to do. also perform your save in controller too if needed.
#Model.IsChanged = true;
//do other functions here also like change button
//if decrease add below
btn.Attributes.Add("onclick", "confirm()");
//if increase remove and perform save.
}
</script>
You can also change the button from that method. There is no good way to do on call events at a server level, unless using blazor, so javascript is your best bet here.
Updated answer per OP:
#model PIC_Program_1._0.Models.JODetails
#using PIC_Program_1._0.Models
#{
ViewBag.Title = "Edit";
PIC_Program_1_0Context db = new PIC_Program_1_0Context();
var currentData = db.JODetails.AsNoTracking().FirstOrDefault(j => j.ID == Model.ID);
Component comp = db.Components.Find(Model.ComponentID);
Item i = db.Items.Find(Model.ItemID);
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>JODetails</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
#Html.HiddenFor(model => model.subDetail)
<p style="color:red">#ViewBag.Error</p>
<div class="form-group">
#Html.LabelFor(model => model.ItemID, "ItemID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ItemID", null, "-- Select --", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ItemID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.item_qty, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#if (ViewBag.isValid == false)
{
#Html.TextBoxFor(model => model.item_qty, new { disabled = "disabled", #Value = Model.item_qty, #readonly = "readonly" })
}
else
{
#Html.EditorFor(model => model.item_qty, new { htmlAttributes = new { onchange = "OnChangeEvent(this)", min = 0, #class = "form-control", #id = "itemQTY"} })
#Html.ValidationMessageFor(model => model.item_qty, "", 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"/>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script type="text/javascript">
function OnChangeEvent(){
alert("value is changed");
var itemQty = $('#itemQTY').val();
if (itemQty < #Model.item_qty) {
btn.Attributes.Add("onclick", "clicked(event)");
}
}
</script>
I'm working on Visual Studio 2017 using Asp.net Mvc 5 to build a web site,My problem is that I can't upload an image from a input file to a server folder
MY CODE:
Create: Views
#using (Html.BeginForm("Create","Jobs",null,FormMethod.Post,new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Jobs</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.JobTitle, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.JobTitle, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.JobTitle, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.JobContent, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.JobContent, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.JobContent, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.JobImage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="upload"/>
#Html.ValidationMessageFor(model => model.JobImage, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CategoryId, "JobType", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CategoryId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CategoryId, "", 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" />
#ViewBag.Message
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create( Jobs jobs,HttpPostedFile upload)
{
try
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
string FileName = Path.GetFileName(upload.FileName);
string path = Path.Combine(Server.MapPath("~/Uploads"), FileName);
upload.SaveAs(path);
jobs.JobImage = FileName;
db.Jobs.Add(jobs);
db.SaveChanges();
}
else{
}
}
}
catch (RetryLimitExceededException /* dex */)
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
ViewBag.CategoryId = new SelectList(db.Categories, "Id", "CategoryName", jobs.CategoryId);
return View(jobs);
}
when I click submit Button nothing change on browser and no error is generated, but when I check Uploads file I found nothing(img file ) ,the same on the database , I don't know where is the error
Note:
Before I added the input file , my code was working perfectly
Any Help Please
I am a new developer and I am trying to populate a drop down list as the result of what was chosen in a previous drop down list. I am stuck and would appreciate a full answer, I think I need a script somewhere but am not sure where to put it, and where to include the script tag.
Controller:
//// GET: TmplRisks/Create
public ActionResult Create()
{
ViewBag.TRisks = db.TmplRisks.ToList();
ViewBag.CategoryL1 = new SelectList(db.CatRiskLevel1Categories, "RiskLevel1CategoryID", "Level1");
//ViewBag.CategoryL2 = new SelectList(db.CatRiskLevel2Categories, "RiskLevel2CategoryID", "Level2");
var model = new TmplRisk();
return View(model);
}
// POST: TmplRisks/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 = "TRiskID,Name,Description,Source,IsKeyRisk,CategoryL1,CategoryL2,Active")] TmplRisk model)
{
if (ModelState.IsValid)
{
db.TmplRisks.Add(model);
db.SaveChanges();
return RedirectToAction("Create");
}
ViewBag.TRisks = db.TmplRisks.ToList();
ViewBag.CategoryL1 = new SelectList(db.CatRiskLevel1Categories, "RiskLevel1CategoryID", "Level1", model.CategoryL1);
//ViewBag.CategoryL2 = new SelectList(db.CatRiskLevel2Categories, "RiskLevel2CategoryID", "Level2", tmplRisk.CategoryL2);
return View(model);
}
public ActionResult FillCategoryLevel2(int category1)
{
var categoryLevel2 = db.CatRiskLevel2Categories.Where(c => c.CatRL1ID == category1);
return Json(categoryLevel2, JsonRequestBehavior.AllowGet);
}
where do i call my FillCategoryLevel2() from?
View:
#model RiAct._02.Models.TmplRisk
#{
ViewBag.Title = "Create";
}
<head>
<script type="text/javascript" src="~/Scripts/FillCategoryLevel2.js"></script>
</head>
<div class="container col-md-12">
<div class="row">
#Html.Partial("List", (IEnumerable<RiAct._02.Models.TmplRisk>)ViewBag.TRisks)
#using (Html.BeginForm())
{
<script>
function FillCategoryLevel2() {
var category1Id = $('#CategoryL1').val();
$.ajax({
url: '/TmplRisks/Create',
type: "GET",
dataType: "JSON",
data: { CategoryL1: category1Id },
success: function (categoryL2) {
$("#CategoryL2").html(""); // clear before appending new list
$.each(categoryL2, function (i, CategoryL2) {
$("#CategoryL2").append(
$('<option></option>').val(CategoryL2.RiskLevel2CategoryID).html(CategoryL2.Level2));
});
}
});
}
</script>
#Html.AntiForgeryToken()
<div class="col-md-6">
<div class="panel panel-default list-panel" id="list-panel">
<div class="panel-heading list-panel-heading">
<div class="panel-title list-panel-title">
New Risk Template
</div>
</div>
<div class="panel-body">
<div class="form-horizontal text-center">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group col-md-offset-1">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-8">
#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 col-md-offset-1">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-8">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group col-md-offset-1">
#Html.LabelFor(model => model.Source, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-8">
#Html.EditorFor(model => model.Source, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Source, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.CategoryL1, new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.DropDownList("CategoryL1", null, "Select One", htmlAttributes: new { #class = "form-control", #onchange = "FillCategoryLevel2()" })
#Html.ValidationMessageFor(m => m.CategoryL1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.CategoryL2, new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.DropDownListFor(m => m.CategoryL2,
new SelectList(Enumerable.Empty<SelectListItem>(), "RislLevel2CategoryID", "Level2"),
"Select one",
new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.CategoryL2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsKeyRisk, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9 text-left">
#Html.EditorFor(model => model.IsKeyRisk)
#Html.ValidationMessageFor(model => model.IsKeyRisk, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Active, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9 text-left">
#Html.EditorFor(model => model.Active)
#Html.ValidationMessageFor(model => model.Active, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="btn-group pull-right">
#Html.ActionLink("Reset", "Create", null, new { #class = "btn btn-default" })
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</div>
</div>
</div>
}
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I'm just trying record student information with an image profile. I want to upload the image as part of the form to application->Image directory and save the image name to the database.
This is my controller
public ActionResult Create([Bind(Include ="StudentId,StudentName,StudentLastName,StudentPhone,StudentAge,StudentEmail,photo")] Student student , HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName);
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}
in my view
#using (Html.BeginForm("Create", "Students", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.StudentName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StudentName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StudentLastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StudentLastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StudentLastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StudentPhone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StudentPhone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StudentPhone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StudentAge, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StudentAge, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StudentAge, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StudentEmail, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StudentEmail, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StudentEmail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.photo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.photo, new { type = "file" })
#Html.ValidationMessageFor(model => model.photo, "", 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>
}
but when i upload, it generates an error message
An exception of type 'System.NullReferenceException'
on this line
file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName
please help me this issue please...
Try this one:
change it:
From
file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName
To
file.SaveAs(HttpContext.Server.MapPath("~/Images/" + file.FileName))
System.NullReferenceException means that something is null at this reported line of code.
In this situation, it should be your HttpPostedFileBase file.
Try run the application in debug mode, and check again the name of your upload field, whether it's set as "file". MVC asp.net using Name attribute to define parameter.
In my case, I'm using a simple <input> to do the upload file and another <img> for displaying:
View:
<!--Displaying: You need some code for this-->
<img src="#ViewBag.ImagePath" alt="Message picture" style="width:100%;">
<!--Uploading-->
#using (Html.BeginForm("Create", "Students", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<!-- Your other part of form -->
<!-- Uploading -->
<input type="file" name="file" />
}
Controller:
// extract only the filename
var fileName = Path.GetFileName(file.FileName);
// initial new path for upload file
var newSPath = Path.Combine(Server.MapPath("~/Images"), fileName);
// store file
file.SaveAs(newSPath);
Try this:-
public ActionResult Create([Bind(Include ="StudentId,StudentName,StudentLastName,StudentPhone,StudentAge,StudentEmail,photo")] Student student , HttpPostedFileBase photo)
{
if (ModelState.IsValid)
{
var fileName=Path.GetFileName(photo.FileName);
var path=Path.Combine(Server.MapPath("~/Images/") + fileName)
photo.SaveAs(path);
db.Students.Add(student);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(student);
}