EF7 MVC ASP.NET File upload in form - c#

I'm trying to upload a file alongside with some model information.
In my table I already have a field 'image' (string) to save the relative URL to the image.
But I don't really know how to do the uploading itself.
I've already read a lot off tutorials, but they all use HttpPostedFileBase, which isn't supported anymore?
This is what I have thus far:
Upload page:
#using (Html.BeginForm("Lets", "Create", FormMethod.Post, new { #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<fieldset>
<div class="form-group">
<div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
#Html.LabelFor(m => m.Lets.Name, new { #class="mdl-textfield__label" })
#Html.TextBoxFor(m => m.Lets.Name, new { #class= "form-control mdl-textfield__input" })
</div>
</div>
<div class="form-group">
<div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
#Html.LabelFor(m => m.Lets.Images)
<input type="file" name="LetsImages" id="m.Lets.Images" /> <br />
</div>
</div>
<div class="form-group">
<div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
#Html.LabelFor(m => m.Lets.Description, new { #class="mdl-textfield__label" })
#Html.TextBoxFor(m => m.Lets.Description, new { #class= "form-control mdl-textfield__input" })
</div>
</div>
<div class="form-group">
<div class="mdl-cell col-md-10 mdl-textfield mdl-js-textfield">
#Html.LabelFor(m => m.Lets.Credits, new { #class="mdl-textfield__label" })
#Html.TextBoxFor(m => m.Lets.Credits, new { #class= "form-control mdl-textfield__input" })
</div>
</div>
<div class="form-group">
<div class="mdl-cell col-md-10">
#Html.LabelFor(m => m.Lets.Group)
#Html.DropDownListFor(m => m.Lets.GroupId, new SelectList(Model.Groups, "Id", "Name"), "-- Selecteer een Groep --", new { #class= "form-control" })
</div>
</div>
#Html.ActionLink("Terug naar het overzicht", "Index", new { }, new { #class= "mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" })
<input type="submit" value="Save" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" />
</fieldset>
}
Controller:
[HttpGet]
public IActionResult Create()
{
var model = new LetsViewModel
{
Lets = new Lets(),
Groups = _kletsContext.Groups.AsEnumerable(),
Letses = _kletsContext.Lets.AsEnumerable().OrderBy(m => m.Name)
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(LetsViewModel model)
{
LetsViewModel viewModel = null;
try
{
if(!ModelState.IsValid)
throw new Exception("The Lets model is not valid!");
var letsImage = "INSERT LOGIC FOR IMAGEUPLOAD HERE?";
model.Lets.UserId = User.GetUserId();
model.Lets.StatusId = 1;
model.Lets.Images = letsImage;
_kletsContext.Lets.Add(model.Lets);
if (_kletsContext.SaveChanges() == 0)
{
throw new Exception("The Lets model could not be saved!");
}
//Success(CreateMessage(ControllerActionType.Create, "klets", model.Name), true);
return RedirectToAction("Index", "Home");
}
catch(Exception ex)
{
ModelState.AddModelError(string.Empty, "Unable to save changes.");
viewModel = new LetsViewModel
{
Lets = model.Lets,
Letses = _kletsContext.Lets.AsEnumerable().OrderBy(m => m.Name)
};
}
return View(viewModel);
}
I've added the place where I think the logic should come?
So what I want to do is:
Upload the Image to a folder
Rename it
Store the relative path as a string to the db.
Thank you

There is no HttpPostedFileBase in MVC6, you have to use IFormFile like this:
public FileDetails UploadSingle(IFormFile file)
{
FileDetails fileDetails;
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
var parsedContentDisposition = ContentDispositionHeaderValue.Parse(file.ContentDisposition);
fileDetails = new FileDetails
{
Filename = parsedContentDisposition.FileName,
Content = fileContent
};
}
return fileDetails;
}

You can upload images using handlers , link to tutorials are
http://www.c-sharpcorner.com/blogs/uploading-files-using-jquery-ajax-in-asp-net1
http://www.binaryintellect.net/articles/f2a2f1ee-e18a-416b-893e-883c800f83f4.aspx
http://www.dotnetjalps.com/2011/12/async-file-upload-with-jquery-and.html?m=1
These tutorials are using jquery to pass the image to the handler and then handler saving the image in the folder. You can rename the image before uploading to the folder and get back the saved image name in response and then save image name along with other model properties.

I eventually got it working by:
include using Microsoft.AspNet.Hosting; and using System.IO;
using System.Net.Http.Headers;
Add public IHostingEnvironment _environment { get; set;}
to your controller (I added it to my commoncontroller, and then it's available to me on my controller)
Then in my create:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(LetsViewModel model, IFormFile LetsImages)
{
LetsViewModel viewModel = null;
try
{
if(!ModelState.IsValid)
throw new Exception("The Lets model is not valid!");
if(LetsImages != null)
{
var targetDirectory = Path.Combine(_environment.WebRootPath, string.Format("images/uploads"));
var fileName = ContentDispositionHeaderValue
.Parse(LetsImages.ContentDisposition)
.FileName
.Trim('"');
var savePath = Path.Combine(targetDirectory, fileName);
var relPath = "/images/uploads/" + fileName;
try
{
LetsImages.SaveAs(savePath);
model.Lets.Images = relPath;
}
catch
{
throw new Exception("There was a problem with saving the file!");
}
}
else
{
model.Lets.Images = null;
}
model.Lets.UserId = User.GetUserId();
model.Lets.StatusId = 1;
_kletsContext.Lets.Add(model.Lets);
if (_kletsContext.SaveChanges() == 0)
{
throw new Exception("The Lets model could not be saved!");
}
//Success(CreateMessage(ControllerActionType.Create, "klets", model.Name), true);
return RedirectToAction("Index", "Home");
}
catch(Exception ex)
{
ModelState.AddModelError(string.Empty, "Unable to save changes.");
viewModel = new LetsViewModel
{
Lets = model.Lets,
Groups = _kletsContext.Groups.AsEnumerable(),
Letses = _kletsContext.Lets.AsEnumerable().OrderBy(m => m.Name)
};
}
return View(viewModel);
}
Just make sure you've created the folder where the images should belong, else it's not going to work without any error!
Thanks everybody for your help!

Related

The uploaded file value gets deleted once the page is re-submitted with incomplete inputs

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();
}

Problem about uploading image to database in ASP.Net MVC

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?

Asp.NET MVC -- Fileupload image value shows null values in httppost method

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

The model item passed into the dictionary is of type System.Collections.Generic.List [duplicate]

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>

MVC 3 Razor - How to handle success/error messages

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>
}
}

Categories

Resources