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?
I’d do something along these lines.