MVC 3 Razor - 如何处理成功/错误消息

时间:2012-11-06 08:58:32

标签: c# asp.net-mvc-3 error-handling

我正在使用MVC3进行新项目,并且我能够将模型中的值传递给我的DAL并成功将数据提交到数据库。作为MVC的新手,我不知道如何处理成功和错误消息。

我想要做的是在提交表单后给用户一些反馈,我不知道我是不是要为此创建一个新的控制器或重用我当前的控制器但是在视图中写一些逻辑来隐藏表格并显示信息。

ActionResult CreateUser是表单,而ActionResult CreateUser使用httppost处理表单提交

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

        }
    }
}

我的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;
        }
    }
}

我对表单提交的看法

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

处理此事的任何建议?

2 个答案:

答案 0 :(得分:1)

    [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");
}

我会沿着这些方向做点什么。

答案 1 :(得分:1)

您可以使用TempData显示消息 对于例如在控制器操作中,您可以将TempData设置为

TempData [“SuccessMsg”] =“记录保存成功。

然后返回要返回的视图,并在该视图中使用TempData [“SuccessMsg”]。

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