Can't upload file in MVC - c#

I have a problem with uploading files to my database, PostedFile is always a null.
Controller:
public ActionResult Create(Sound sound)
{
if (sound.PostedFile != null && sound.PostedFile.ContentLength > 0)
{
MemoryStream temp = new MemoryStream();
sound.PostedFile.InputStream.CopyTo(temp);
sound.Data = temp.ToArray();
db.SoundsTable.Add(sound);
db.SaveChanges();
ViewBag.Message = "DONE";
}
else
{
ViewBag.Message = "ERR";
}
return RedirectToAction("Index");
}
Model:
public class Sounds : DbContext
{
public Sounds()
: base("name=Sounds")
{
}
public virtual DbSet<Sound> SoundsTable { get; set; }
}
public class Sound
{
public int Id { get; set; }
public string Name { get; set; }
[MaxLength(8388608)]
public byte[] Data { get; set; }
[NotMapped]
[Required(ErrorMessage = "Please select file.")]
public HttpPostedFileBase PostedFile { get; set; }
}
View:
#model WebApp.Models.Sound
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
<div class="form-horizontal">
<h4>Sound</h4>
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })<br />
#Html.TextBoxFor(model => model.PostedFile, new { type = "file" })<br />
#Html.ValidationMessageFor(model => model.PostedFile, "", new { #class = "error" })<br />
<input type="submit" value="UPLOAD" />
<br />
#ViewBag.Message
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
}
Everything works fine with Name value being send from View to Controller. But I cant get working sending PostedFile value, as it is always a null.

enctype = multipart/form-data is indeed required
#using (Html.BeginForm("Create", //Your action
"Test", //Your controller
FormMethod.Post,
new { enctype = "multipart/form-data"}))
{
<div class="form-horizontal">
<h4>Sound</h4>
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })<br />
#Html.TextBoxFor(model => model.PostedFile, new { type = "file" })<br />
#Html.ValidationMessageFor(model => model.PostedFile, "", new { #class = "error" })<br />
<input type="submit" value="UPLOAD" />
<br />
#ViewBag.Message
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
}

try this:
#using (Html.BeginForm("Create", "Test", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
//other controls here
<input type="file" name="postedFile" id="fileInputId" />
//submit button here }
Then your controller:
[HttpPost]
public ActionResult Create(Sound model, HttpPostedFileBase postedFile)
{
//do stuff
}
Make sure that the name in input file element is the same as the parameter name in the controller.

Related

how to add image in Asp.net?

I cannot add image in about -> post method. This is my code please help.
This is my controller section:
ActionResult Register(Admin adm)
{
string fileName = Path.GetFileNameWithoutExtension(adm.ImageFile.FileName);
string exe = Path.GetExtension(adm.ImageFile.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssfff") + exe;[enter image description here][1]
adm.Adm_Image_path = "~/Image/" + fileName;
fileName = Path.Combine(Server.MapPath("~/Image/"), fileName);
adm.ImageFile.SaveAs(fileName);
// Upload_Image(adm.ImageFile);
if (ModelState.IsValid)
{
if (adm.Adm_Password == adm.Adm_Confirm_Password)
{
adm.Adm_Type = "Admin";
db.admin.Add(adm);
db.SaveChanges();
return RedirectToAction("Login", "Home");
}
}
return View();
}
View section here
<div class="form-group">
#Html.LabelFor(x => x.Adm_Image_path, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="ImageFile" id="ImageFile" value="ImageFile" required />
#Html.ValidationMessageFor(x => x.Adm_Image_path, "", new { #class="text-danger"})
</div>
</div>
<input type="submit" value="Save" class="btn btn-default" />`
I cannot upload the image in the specific section.
Use Below code.
Model Class:
public class Admin
{
public string ImagePath { get; set; }
public HttpPostedFileBase ImageFile { get; set; }
}
Controller:
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(Admin adm)
{
string fileName = Path.GetFileNameWithoutExtension(adm.ImageFile.FileName);
string exe = Path.GetExtension(adm.ImageFile.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssfff") + exe;
adm.ImagePath = "~/Images/" + fileName;
fileName = Path.Combine(Server.MapPath("~/Images/"), fileName);
adm.ImageFile.SaveAs(fileName);
//Upload_Image(adm.ImageFile);
if (ModelState.IsValid)
{
//if (adm.Adm_Password == adm.Adm_Confirm_Password)
//{
// adm.Adm_Type = "Admin";
// db.admin.Add(adm);
// db.SaveChanges();
// return RedirectToAction("Login", "Home");
//}
return View();
}
else
{
return View();
}
}
View:
#model testProject.Models.Admin
#{
ViewBag.Title = "Register";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Register</h2>
#using (Html.BeginForm("Register", "Signup", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
#Html.LabelFor(x => x.ImagePath, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="ImageFile" id="ImageFile" value="ImageFile" required />
#Html.ValidationMessageFor(x => x.ImagePath, "", new { #class = "text-danger" })
</div>
</div>
<input type="submit" value="Save" class="btn btn-default" />
}
Hope this will surely help you.

I want to save input from html to txt file (ASP.NET MVC)

I want to create a register site that will take user information and save it to a text file (it needs to be a text file, not a database).
This is my controller:
public IActionResult Register()
{
UserRLModel cos = new UserRLModel();
string root = #"D:\dotNET\RiderProjects\WebApplication3\UserInfo\Users.txt";
using (StreamWriter sw = new StreamWriter(root))
{
sw.WriteLine(cos.Name);
};
return View(cos.Name);
}
This is my model:
using System;
namespace WebApplication3.Models
{
public class UserRLModel
{
public string Name { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public DateTime Date { get; set; }
}
}
This is my view:
#model WebApplication3.Models.UserRLModel
#{
ViewBag.Title = "Register";
Layout = "_Layout";
}
#using (Html.BeginForm("Register", "UserRL", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Wprowadź dane użytkownika</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => Model.Name, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(model => Model.Name, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Dodaj" class="btn btn-default" />
#Html.ActionLink("Anuluj", "Index", null, htmlAttributes: new { #class = "btn btn-danger" })
</div>
</div>
}

How can I fill / populate DropDown with my IEnumerable<Model> value ASP.NET MVC

I tried to set my dropdown list values from my model as it is the value I need to see in the dropdown
But I'm facing an error:
The type arguments for method
'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper,
System.Linq.Expressions.Expression>,
System.Collections.Generic.IEnumerable,
string)' cannot be inferred from the usage. Try specifying the type
arguments explicitly.
And here is my code:
#model IEnumerable<Language>
#using Web.Helpers
#{
ViewBag.Title = "";
}
<div class="">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2><i class="fa fa-filter"></i> </h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br />
#using (Html.BeginForm("Settings","Language", FormMethod.Post, new { #class = "form-horizontal form-label-left" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="col-md-12 col-sm-12">
<div class="col-md-12 col-sm-12">
#Html.DropDownListFor(WHATTOWRITEHERE, new SelectList(ViewBag.Languagess, "Id", "Name"), new { #class = "form-control" })
</div>
</div>
}
}
}
}
}
}
Controller action:
public ActionResult Settings()
{
List<Language> activeL = LanguageController.GetAll();
ViewBag.Languagess = activeLanguages;
return View(activeL);
}
Maybe I could delete ViewBag.Languagess at all, so I can use (Model, "Id", "Name") there instad of (ViewBag.Languagess, "Id", "Name")
Since you've requested how to do this with a strongly typed model instead of a ViewBag....
Right now your view requires a model of type IEnumerable<Language>. Change this to be a new class that holds all values your page needs.
public class LanguagesViewModel
{
List<Language> ActiveLanguages { get; set; }
}
Then in your controller:
var model = new LanguagesViewModel();
model.ActiveLanguages = activeLanguages;
return View(model);
Change your View to require a LanguagesViewModel:
#model LanguagesViewModel
Now you won't be working with the dynamic view bag.
#Html.DropDownListFor(m => m.LanguageId, Model.ActiveLanguages, new { #class = "form-control" })
public ActionResult Settings()
{
List<Language> activeL = LanguageController.GetAll();
ViewBag.Languages = activeLanguages.Select(item => new SelectListItem{
Text = item.Name,
Value = item.Id
});
return View(activeL);
}
#Html.DropDownListFor(m => m.LanguageId, ViewBag.Languages, new { #class = "form-control" })
You need to write html like this
#Html.DropDownListFor(WHATEVER, new SelectList(ViewBag.languages, "Id", "Name"), new { #class = "form-control" })
And in your controller
public ActionResult Settings()
{
List<Language> activeL = LanguageController.GetAll();
ViewBag.Languagess = activeL;
return View();
}
I thing your model could been an other type like Settings.
public class SettingsModel
{
public int LanguageId { get; set; }
}
public class Language
{
public int Id { get; set; }
public string Name { get; set; }
}
.cshtml
#model SettingsModel
#using Web.Helpers
#{
ViewBag.Title = "";
}
<div class="">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2><i class="fa fa-filter"></i> </h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br />
#using (Html.BeginForm("Settings","Language", FormMethod.Post, new { #class = "form-horizontal form-label-left" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="col-md-12 col-sm-12">
<div class="col-md-12 col-sm-12">
#Html.DropDownListFor(model => model.LanguageId, new SelectList(ViewBag.Languagess, "Id", "Name"), new { #class = "form-control" })
</div>
</div>
}
}
}
}
}
}
controller
[HttpGet]
public ActionResult Language()
{
List<Language> activeL = LanguageController.GetAll();
ViewBag.Languagess = activeLanguages;
return View();
}
[HttpPost]
public ActionResult Language(SettingsModel settings)
{
Language selectedLanguage = LanguageController.GetAll().Where(l => l.Id == settings.LanguageId).SingleOrDefault();
//... your post operations.
}
model
public class LanguageViewModel
{
public int LanguageId { get; set; }
public IEnumerable<Language> ActiveLanguages{get; set;}
}
public class Language
{
public int Id { get; set; }
public string Name { get; set; }
}
Controller
[HttpGet]
public ActionResult Language()
{
var languageViewModel = new LanguageViewModel
{
ActiveLanguages = LanguageController.GetAll();
}
return View(languageViewModel);
}
View
#model LanguageViewModel
#using Web.Helpers
#{
ViewBag.Title = "";
}
<div class="">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2><i class="fa fa-filter"></i> </h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<br />
#using (Html.BeginForm("Settings","Language", FormMethod.Post, new { #class = "form-horizontal form-label-left" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="col-md-12 col-sm-12">
<div class="col-md-12 col-sm-12">
#Html.DropDownListFor(model => model.LanguageId, new SelectList(Model.ActiveLanguages, "Id", "Name"), new { #class = "form-control" })
</div>
</div>
}
}
}
}
}
}
It would work like in this example:
#{
List<SelectListItem> listItems= new List<SelectListItem>();
listItems.Add(new SelectListItem
{
Text = "Exemplo1",
Value = "Exemplo1"
});
listItems.Add(new SelectListItem
{
Text = "Exemplo2",
Value = "Exemplo2",
Selected = true
});
listItems.Add(new SelectListItem
{
Text = "Exemplo3",
Value = "Exemplo3"
});
}
#Html.DropDownListFor(model => model.tipo, listItems, "-- Select Status --")

Capturing date time from the view into the database MVC

I created MVC application that has a text box posted to the database. When the text box is posted, I want to capture today's date from the view and store it into the table. How do I capture the date and time the view that posted and how do I pass this information into row Date within the database? Appreciate any help.
Controller
[HttpGet]
public ActionResult Pay(int accountNumber)
{
return View();
}
[HttpPost]
public ActionResult Pay(Payments payment )
{
if(ModelState.IsValid)
{
DB.Payment.Add(payment);
DB.SaveChanges();
var service = new Accounts(DB);
service.Updatepayee(payment.AccountNumber);
return RedirectToAction("Index", "Home");
}
return View();
}
Payments Class
public class Payments
public int Id { get; set; }
[Required]
[DataType(DataType.Currency)]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public decimal Amount { get; set; }
[Required]
public int AccountNumber {get; set;}
[RegularExpression(#"(^$)|(^\d{2}/\d{2}/\d{4})|(^((\d{1})|(\d{2}))/((\d{1})|(\d{2}))/(\d{4})\s((\d{1})|(\d{2}))[:]{1}((\d{1})|(\d{2}))[:]{1}((\d{1})|(\d{2}))\s((AM)|(PM)))", ErrorMessage = "Invalid Date")]
public DateTime TransactionDate { get; set; }
//Navigation property to check the account
public virtual AccountNumber accountNumber { get; set; }
}
Pay View
#model Credits.View.Payments
#{
ViewBag.Title = "Pay"; }
<h2>Payments</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Transaction</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Amount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Amount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Amount, "", 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", "Home") </div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval") }
Couldn't you set it in the controller:
[HttpPost]
public ActionResult Pay(Payments payment )
{
if(ModelState.IsValid)
{
payment.TransactionDate = DateTime.Now.ToUniversalTime();
DB.Payment.Add(payment);
DB.SaveChanges();
[HttpPost]
public ActionResult Pay(Payments payment )
{
var d=DateTime.Now.ToUniversalTime();
if(ModelState.IsValid)
{
Payments p=new() Payments{
AccountNumber=p.AccountNumber,
Amount=payment.Amount,
TransactionDate=d
};
DB.Payment.Add(p);
DB.SaveChanges();

ViewModel properties null on submit

I need two models in my view, so I created ViewModel that combines them. That is on getting method. But on the Post, my input type=submit is returning ViewModel, but values of properties inside are null. Any advice?
These are my actions for Get and Post
[HttpGet]
public ActionResult Report(int id)
{
using (SkolskaBibliotekaDBModel db = new SkolskaBibliotekaDBModel())
{
ReportZaPrikaz RZP = new ReportZaPrikaz();
var komentar = db.Komentar.FirstOrDefault(x => x.KomentarID == id);
RZP.kzp = new KomentarZaPrikaz()
{
KomentarID = komentar.KomentarID,
KomentarText = komentar.KomentarText,
KorisnikID = komentar.KorisnikID,
Reported = komentar.Reported,
VremeKomentara = komentar.VremeKomentara,
Ime = komentar.Korisnik.Ime,
Prezime = komentar.Korisnik.Prezime,
PicPath = komentar.Korisnik.PicPath,
VoteUp = komentar.VoteUp,
VoteDown = komentar.VoteDown
};
RZP.report = db.PrijavaKomentara.Create();
return View("Report",RZP);
}
}
[HttpPost]
public void Report(ReportZaPrikaz RZP)
{
using (SkolskaBibliotekaDBModel db = new SkolskaBibliotekaDBModel())
{
db.PrijavaKomentara.Add(RZP.report);
db.SaveChanges();
}
}
this is my viewmodel:
namespace SkolskaBiblioteka.ViewModels
{
public class ReportZaPrikaz
{
public KomentarZaPrikaz kzp;
public PrijavaKomentara report;
}
}
and this is my view:
#model SkolskaBiblioteka.ViewModels.ReportZaPrikaz
#using SkolskaBiblioteka.ViewModels
#{
ViewBag.Title = "Пријава коментара";
}
<div class="container">
#Html.Partial("_Komentar", Model.kzp)
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>PrijavaKomentara</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#{
Model.report.KorisnikId = ((KorisnikZaPrikaz)Session["Korisnik"]).KorisnikId;
}
#Html.HiddenFor(x => x.report.KorisnikId)
#{
Model.report.KomentarId = Model.kzp.KomentarID;
}
#Html.HiddenFor(x => x.report.KomentarId)
#{
Model.report.VremePrijave = DateTime.Now;
}
#Html.HiddenFor(x => x.report.VremePrijave)
<div class="form-group">
#Html.LabelFor(model => model.report.Tekst, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.report.Tekst, new { htmlAttributes = new { #class = "form-control" } })
</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>
These conditions show up when I hit submit button.
The default model-binder would not bind fields. Try to use properties instead:
public class ReportZaPrikaz
{
public KomentarZaPrikaz kzp { get; set; }
public PrijavaKomentara report { get; set; }
}

Categories