I would like the page to saves the uploaded file even if the submit button is clicked at the time where not all the form is filled unless all the form is completed.
<div class="form-group">
#Html.LabelFor(model => model.cvURL, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-lg-10">
#Html.TextBoxFor(model => model.cvURL, new { type = "file" })
#Html.ValidationMessageFor(model => model.cvURL)
</div>
</div>
public ActionResult RegisterCandidates(CandidateRegisteration can, HttpPostedFileBase cvURL)
{
if (ModelState.IsValid)
{
if (CheckFileType(cvURL.FileName))
{
var fileName = Path.GetFileName(cvURL.FileName);
var path = Path.Combine(Server.MapPath("~/CVuploads"), fileName);
can.cvURL = cvURL.FileName;
cvURL.SaveAs(path);
db.CandidateRegisteration.Add(can);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
ViewBag.emailExists = "Not Right extention";
}
}
return View();
}
I am trying to upload images to database in MVC. There is not any error while uploading but then looks NULL in database.
Create.cshtml
<div class="form-group">
#Html.LabelFor(model => model.Foto, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="ImageData" id="ImageData" />
</div>
</div>
[HttpPost]
public ActionResult MakaleOlustur(Makale m, HttpPostedFileBase file)
{
try
{
using (MvcBlogContext context = new MvcBlogContext())
{
Makale _makale = new Makale();
if (file != null && file.ContentLength > 0)
{
MemoryStream memoryStream = file.InputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
file.InputStream.CopyTo(memoryStream);
}
_makale.Foto = memoryStream.ToArray();
}
_makale.Baslik = m.Baslik;
_makale.OlusturmaTarihi = DateTime.Now;
_makale.Icerik = m.Icerik;
context.Makale.Add(_makale);
context.SaveChanges();
return RedirectToAction("Makale", "Admin");
}
}
catch (Exception ex)
{
throw new Exception("Eklerken hata oluştu" + ex.Message);
}
}
Interestingly, this exactly same codes work in another project. Can you help me?
I have a MultipartForms in Which I Could upload an Image and other form values.While, the form values are rightfully received through the FormCollection Property whereas the Upload file always shows the null value in HttpPostedFileBase Property.I go through forums but I couldn't get Where went Wrong. Here, Is What I done Please go through it and Said what Went Wrong.Thanks friend.
enter code here
cshtml:
#using (Html.BeginForm("Create", "StaffRegistration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="StaffImage" id="StaffImage" />
}
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection,HttpPostedFileBase File)
{
try
{
// TODO: Add insert logic here
StaffRegistration StaffReg = new StaffRegistration();
StaffReg.FirstName = collection["FirstName"].ToString();
StaffReg.LastName = collection["LastName"].ToString();
StaffReg.DateOfBirth = DateTime.Parse(collection["DateofBirth"]);
StaffReg.Nationality = collection["Nationality"].ToString();
StaffReg.Gender = collection["Gender"].ToString();
StaffReg.MaritalStatus = collection["MaritalStatus"].ToString();
StaffReg.BloodGroup = collection["BloodGroup"].ToString();
StaffReg.StaffName = collection["StaffName"].ToString();
StaffReg.MiddleName = collection["MiddleName"].ToString();
HttpPostedFileBase file = Request.Files["StaffImage"];
StaffRegistrationBusSer StaffRegBusSer = new StaffRegistrationBusSer();
StaffRegBusSer.AddStaffReg(StaffReg,file);
return RedirectToAction("Index");
}
DataLayer
public bool AddStaffRegistraiton(StaffRegistration staffRegistration,HttpPostedFileBase File)
{
staffRegistration.StaffImage = ConvertToByte(File);
using(SqlConnection Con = new SqlConnection(ConnectionString))
{
SqlParameter paramImage = new SqlParameter();
paramImage.ParameterName = "#StaffImage";
paramImage.Value = staffRegistration.StaffImage;
Cmd.Parameters.Add(paramImage);
Con.Open();
Cmd.ExecuteNonQuery();
}
return true;
}
ConvertToByte function:
public byte[] ConvertToByte(HttpPostedFileBase Image)
{
byte[] imagebyte = null;
BinaryReader Reader = new BinaryReader(Image.InputStream);
imagebyte = Reader.ReadBytes((int)Image.ContentLength);
return imagebyte;
}
cshtml page:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="form-group">
#Html.LabelFor(model => model.StaffName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StaffName)
#Html.ValidationMessageFor(model => model.StaffName)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="file" name="StaffImage" id="StaffImage" />
</div>
</div>
}
Actually I have to include multipart/form in View level, Instead of the particular upload files.Then, I Modified like this in .cshtml page. Now, my code works fine
I'm new to asp.net and this is my first application.
I'm developing an application that manages insurance requests. The model Request contains a file upload. the addDemand (adds a request)requires a member(adherent) to be logged in. Every time I try to run the addDemande I get the error:
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Mutuelle.Domain.Entities.Demande]', but this dictionary requires a model item of type 'Mutuelle.Domain.Entities.Demande'.
Here's the controller:
public ActionResult AddDemande()
{
Demande demande = new Demande();
return View(demande);
}
[HttpPost]
public ActionResult AddDemande([Bind(Exclude = "fichier")]Demande demande, HttpPostedFileBase fichier)
{
try
{
if (!ModelState.IsValid)
{
return View();
}
else
{
BinaryReader fichierReader = new BinaryReader(fichier.InputStream);
byte[] fichiers = fichierReader.ReadBytes(fichier.ContentLength);
demande.fichier = fichiers;
AdherentDService adherentService = new AdherentDService();
Adherent adherent = (Adherent)Session["logedAd"];
demande.nomBeneficiaire = adherent.nom;
demande.eMailBeneficiaire = adherent.eMail;
demande.beneficiare = adherent;
adherent.listDemandes.Add(demande);
adherentService.Updateadherent(adherent);
demande.beneficiare = adherent;
adherentService.CreateaDemande(demande);
Session.Remove("logedAd");
Session.Add("logedAd", adherent);
return RedirectToAction("Demandes");
}
}
catch
{
return RedirectToAction("Index", "Home");
}
}
And here's the View:
model Mutuelle.Domain.Entities.Demande
#{
ViewBag.Title = "AddDemande";
}
<h2>AddDemande</h2>
#using (Html.BeginForm("AddDemande", "Adherent", FormMethod.Post, new { #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Demande</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Nomrubrique, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Nomrubrique)
#Html.ValidationMessageFor(model => model.Nomrubrique)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.fichier, new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input style="margin-left:0px;cursor:pointer;" type="file" name="fichier" id="fichier" />
</div>
</div>
I am using MVC3 for a new project and I am able to pass the values from my model to my DAL and successfully submit data to the database. Being new to MVC I am not sure how to handle success and error messages.
What I want to do is give the user some feedback after the form is submitted and I don't know if I am meant to create a new controller for this or reuse my current controller but write some logic in the view to hide the form and show the message.
ActionResult CreateUser is the form and ActionResult CreateUser with httppost handles form submission
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UserManager.Models;
namespace UserManager.Controllers
{
public class UserManagerController : Controller
{
//
// GET: /UserManager/
public ActionResult Index()
{
try
{
var data = new UserManager.Models.UserManagerTestEntities();
return View(data.vw_UserManager_Model_Add_Users.ToList());
}
catch (Exception ex)
{
return View(ViewBag);
}
}
public ActionResult LookUpGroupName(string q, int limit)
{
//TODO: Map list to autocomplete textbox control
DAL d = new DAL();
List<string> groups = d.groups();
var GroupValue = groups
.Where(x => x.Contains(q))
.OrderBy(x => x)
.Take(limit)
.Select(r => new { group = r });
// Return the result set as JSON
return Json(GroupValue, JsonRequestBehavior.AllowGet);
}
public ActionResult CreateUser()
{
//var data = new UserManager.Models.UserManagerTestEntities();
ViewBag.Message = "Create New User";
return View();
}
[HttpPost]
public ActionResult CreateUser(vw_UserManager_Model_Add_Users newUser)
{
try
{
if (ModelState.IsValid)
{
//var data = new UserManager.Models.UserManagerTestEntities();
// Pass model to Data Layer
List<string> outcome = UserManager.DAL.CreateUser(newUser);
//data.SaveChanges();
}
return View();
}
catch (Exception ex)
{
return View(ex.ToString());
}
}
}
}
My DAL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using UserManager.Models;
using System.Security.Cryptography;
using System.Web.Security;
namespace UserManager
{
public class DAL
{
#region hashingpassword
private static string CreateSalt(int size)
{
// Generate a cryptographic random number.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);
// Return a Base64 string representation of the random number.
return Convert.ToBase64String(buff);
}
private static string CreatePasswordHash(string pwd, string salt)
{
string saltAndPwd = string.Concat(pwd, salt);
string hashedPwd =
FormsAuthentication.HashPasswordForStoringInConfigFile(
saltAndPwd, "sha1");
return hashedPwd;
}
#endregion
private static SqlConnection BradOnline()
{
UserManagerTestEntities DBContext = new UserManagerTestEntities();
string connectionstring = DBContext.Database.Connection.ConnectionString;
SqlConnection conn = new SqlConnection(connectionstring);
return conn;
}
public List<string> groups()
{
List<string> groups = new List<string>();
using (SqlConnection conn = BOnline())
{
using (var command = new SqlCommand("Select name from aspnet_Custom_Groups", conn))
{
try
{
conn.Open();
command.CommandType = CommandType.Text;
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet dataset = new DataSet();
adapter.Fill(dataset);
foreach (DataRow dr in dataset.Tables[0].Rows)
{
groups.Add(dr["name"].ToString());
}
}
catch (SqlException ex)
{
ex.ToString();
}
return groups;
}
}
}
public static List<string> CreateUser(Models.vw_UserManager_Model_Add_Users newUser)
{
List<string> outcome = new List<string>();
try
{
using (SqlConnection conn = BOnline())
{
conn.Open();
UserManager.Models.vw_UserManager_Model_Add_Users model = new Models.vw_UserManager_Model_Add_Users();
using (var command = new SqlCommand("sp_UserManager_Add", conn))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#salutation", SqlDbType.NVarChar).SqlValue = newUser.salutation;
command.Parameters.Add("#username", SqlDbType.NVarChar).SqlValue = newUser.email;
command.Parameters.Add("#firstname", SqlDbType.NVarChar).SqlValue = newUser.firstname;
command.Parameters.Add("#lastname", SqlDbType.NVarChar).SqlValue = newUser.lastname;
command.Parameters.Add("#password", SqlDbType.NVarChar).SqlValue = newUser.password;
string salt = CreateSalt(20);
string passwordSalt = CreatePasswordHash(newUser.password, salt);
command.Parameters.Add("#passwordsalt", SqlDbType.NVarChar).SqlValue = passwordSalt;
command.Parameters.Add("#passwordquestion", SqlDbType.NVarChar).SqlValue = "test";
command.Parameters.Add("#passwordanswer", SqlDbType.NVarChar).SqlValue = "test";
command.Parameters.Add("#email", SqlDbType.NVarChar).SqlValue = newUser.email;
command.Parameters.Add("#CurrentTimeUtc", SqlDbType.DateTime).SqlValue = DateTime.UtcNow;
switch (newUser.isactive)
{
case true:
command.Parameters.Add("#isapproved", SqlDbType.TinyInt).SqlValue = 1;
break;
case false:
command.Parameters.Add("#isapproved", SqlDbType.TinyInt).SqlValue = 0;
break;
}
switch (newUser.alfConnect)
{
case true:
command.Parameters.Add("#Connect", SqlDbType.TinyInt).SqlValue = 1;
break;
case false:
command.Parameters.Add("#Connect", SqlDbType.TinyInt).SqlValue = 0;
break;
}
switch (newUser.alfIntelligence)
{
case true:
command.Parameters.Add("#Intelligence", SqlDbType.TinyInt).SqlValue = 1;
break;
case false:
command.Parameters.Add("#Intelligence", SqlDbType.TinyInt).SqlValue = 0;
break;
}
switch (newUser.brad)
{
case true:
command.Parameters.Add("#rad", SqlDbType.TinyInt).SqlValue = 1;
break;
case false:
command.Parameters.Add("#rad", SqlDbType.TinyInt).SqlValue = 0;
break;
}
command.Parameters.Add("#ApplicationName", SqlDbType.NVarChar).SqlValue = "bradlink";
command.Parameters.Add("#Group", SqlDbType.NVarChar).SqlValue = newUser.group_name;
int rowsCreated = command.ExecuteNonQuery();
if (rowsCreated > 0)
{
outcome.Add("New user created successfully.");
foreach (SqlParameter p in command.Parameters)
{
outcome.Add(p.Value.ToString());
}
}
}
}
}
catch (Exception ex)
{
List<string> error = new List<string>();
error.Add("Error creating new user. Check error message for more details.");
error.Add(ex.Message);
}
return outcome;
}
}
}
My view for form submission
<!-- Declare model to be used for view -->
#model UserManager.Models.vw_UserManager_Model_Add_Users
#{
ViewBag.Title = "Create New User";
}
<h2>
CreateUser</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>New User Details</legend>
<div class="editor-label">
#Html.LabelFor(Model => Model.salutation)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.salutation)
#Html.ValidationMessageFor(model => Model.salutation)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.firstname)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.firstname)
#Html.ValidationMessageFor(model => Model.firstname)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.lastname)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.lastname)
#Html.ValidationMessageFor(model => Model.lastname)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.password)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.password)
#Html.ValidationMessageFor(model => Model.password)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.email)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.email)
#Html.ValidationMessageFor(model => Model.email)
</div>
<div class="editor-label">
#Html.LabelFor(Model => Model.isactive)
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.isactive)
#Html.ValidationMessageFor(model => Model.isactive)
</div>
<div class="editor-label">
#Html.Label("Group Name")
<!-- GroupName -->
</div>
<div class="editor-field">
#Html.EditorFor(model => Model.group_name, new { ID = "group_name" })
#Html.ValidationMessageFor(model => Model.group_name)
</div>
<div class="editor-label">
#Html.Label("Subscription Options")
<!-- GroupName -->
</div>
<div class="editor-field">
#Html.Label("Connect")
#Html.CheckBoxFor(Model => Model.Connect)
#Html.Label("ALF Intelligence")
#Html.CheckBoxFor(Model => Model.Intelligence)
#Html.Label("BRAD")
#Html.CheckBoxFor(Model => Model.rad)
</div>
<p>
<input type="submit" value="Create" onclick="return submitWith();"/>
<span id="validationMessage"></span>
</p>
</fieldset>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
}
<script type="text/javascript">
// Count checkboxes that are checked.
function submitWith() {
var checkedCount = $("input:checked").length;
var valid = checkedCount > 0;
if (!valid) {
$('#validationMessage').html('You must select at least one option');
}
return valid;
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#group_name").autocomplete('#Url.Action("LookUpGroupName")', // Call LookUpGroupName ActionResult in UserManager Controller
{
dataType: 'json',
parse: function (data) {
var rows = new Array();
for (var i = 0; i < data.length; i++) {
rows[i] = {
data: data[i],
value: data[i].group,
result: data[i].group
}
}
return rows;
},
formatItem: function (row, i, max) {
return row.group;
},
width: 300,
highlight: false,
multiple: false
}); // End of autocomplete
});
</script>
Any advice for handling this?
[HttpPost]
public ActionResult CreateUser(vw_UserManager_Model_Add_Users newUser)
{
try
{
if (ModelState.IsValid)
{
//var data = new UserManager.Models.UserManagerTestEntities();
// Pass model to Data Layer
List<string> outcome = UserManager.DAL.CreateUser(newUser);
//data.SaveChanges();
}
return View();
}
catch (Exception ex)
{
return RedirectToAction("showError", ex.Message);
}
}
public ActionResult showError(String sErrorMessage)
{
//All we want to do is redirect to the class selection page
ViewBag.sErrMssg = sErrorMessage;
return PartialView("ErrorMessageView");
}
I'd do something along these lines.
You Can use TempData for showing the Message.
For e.g. In your controller action you can set the TempData Like
TempData["SuccessMsg"] ="Record Saved Successfully.
Then return the view you want to return and Use TempData["SuccessMsg"] in that View.
e.g.
#model UserManager.Models.vw_UserManager_Model_Add_Users
#{
ViewBag.Title = "Create New User";
}
<h2>
CreateUser</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
if(TempData["SuccessMsg"]!=null)
{
<div>TempData["SuccessMsg"].ToString()</div>
}
}