繁体   English   中英

将数据插入ASP.NET中的SQL数据库

[英]Insert data into sql database in ASP.NET

我面临从表单获取值并将其传递给控制器​​的问题。

AddUser.cshtml

@model SecureMedi.Models.Users

<form asp-controller="Index" asp-action="AddUser" method="post">
    <div class="form-group">
        <label asp-for="Username">Username</label>
        <input asp-for="Username" class="form-control" />
    </div>
    <!-- / form-group -->
    <div class="form-group">
        <label asp-for="Role">Username</label>
        <input asp-for="Role" class="form-control" />
    </div>
    <!-- / form-group -->
    <button type="submit" class="btn btn-primary">Add User</button>
</form>
<!-- / form -->

UsersDAL.cs(数据访问层)

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using SecureMedi.Models;

namespace SecureMedi.DAL {
    public class UsersDAL {
        public void Insert(Users u) {
            string connectionstring = "MY_CONNECTION_STRING";
            SqlConnection conn = new SqlConnection(connectionstring);
            SqlCommand cmd = new SqlCommand(String.Format("CREATE USER {0} WITHOUT LOGIN", u.Username), conn);
            SqlCommand cmd2 = new SqlCommand(String.Format("ALTER ROLE {1} ADD MEMBER {0}", u.Username, u.Role), conn);

            try {
                conn.Open();

                using(conn) {
                    cmd.Transaction = conn.BeginTransaction();
                    cmd.ExecuteNonQuery();
                    cmd2.Transaction = cmd.Transaction;
                    cmd2.ExecuteNonQuery();
                    cmd2.Transaction.Commit();
                }
            } finally {
                if (conn != null) {
                    conn.Close();
                }
            }

        }
    }
}

Users.cs(模型)

namespace SecureMedi.Models {
    public class Users {
        public string Username {
            get;
            set;
        }
        public string Role {
            get;
            set;
        }
    }
}

HomeController.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using nmvs_db.dal;
using nmvs_module;
using nmvs_module.util;
using SecureMedi.Models;
using SecureMedi.DAL;

namespace SecureMedi.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult AddUser(Users u)
        {
            UsersDAL ud = new UsersDAL();            
            ud.Insert(u);
            return View(u);
        }
    }
}

在这里,我面临两个问题:

1)每当我在浏览器中导航到/AddUser ,就会自动调用AddUser方法。 相反,我仅在单击form按钮时才想调用AddUser方法。

2)由于AddUser被自动调用(第1点),我从u.Usernameu.Role检索的值为null.

出于调试目的,如果我修改控制器方法如下:

public ActionResult AddUser(Users u) {
    if (u.Username == null)
        u.Username = "testuser";
    if (u.Role == null)
        u.Role = "SecureMediUsers";
    UsersDAL ud = new UsersDAL();
    ud.Insert(u);
    return View(u);
}

在DAL中传递的唯一值是UsernameRole的硬编码值,如上所示,在这里我希望从form输入值中获取这些值。

您需要单独的GET和POST方法。 GET将是

[HttpGet] // this attribute is optional since its the default
public ActionResult AddUser()
{
    var model = new Users();
    return View(model);
}

当前需要使用的方法和方法都需要标记HttpPostAttribute 另外,您应该检查ModelState是否无效,如果无效,请立即返回视图,以便用户可以更正验证错误,如果无效,请保存然后重定向。

[HttpPost]
public ActionResult AddUser(Users u)
{
    if (!ModelState.IsValid)
    {
        return View(u);
    }
    UsersDAL ud = new UsersDAL();            
    ud.Insert(u);
    return RedirectToAction("Index", "Home"); // redirects to ../Home/Index
}

您还应该考虑添加验证属性(例如,假设属性的值不能为null[Required]属性),并在视图中为客户端和服务器端验证添加验证消息占位符(请参阅模型验证简介 )。

作为旁注,您的模型描述为单个User,因此该类应为public class User (而不是复数)

将asp-controller =“ Index”更改为asp-controller =“ Home

我不知道您是否正在使用临时代码来使控制器正常工作,但不要忘记保护自己免受SQL注入,并在出现故障时回滚事务。

SqlConnection conn = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand(String.Format("CREATE USER {0} WITHOUT LOGIN", u.Username), conn);
SqlCommand cmd2 = new SqlCommand(String.Format("ALTER ROLE {1} ADD MEMBER {0}", u.Username, u.Role), conn);

使用SqlParameterCollection加载SqlCommand的示例:(不是ASP.NET项目)

“ nErrorMsg”是为封装方法提供的参数:

try
  {
    nErrorMsg = nErrorMsg.Truncate(2000);

    using (SqlConnection sqlErrorLogConn = new SqlConnection(SqlConnString.ErrorLogConn))
    {
      try
      {
        sqlErrorLogConn.Open();
      }
      catch (Exception)
      {
        MessageBox.Show("There was an error whilst opening the connection with the database - (WriteToErrorLog)", "Connection Error", 0, MessageBoxIcon.Error);
        return;
      }

      using (SqlCommand sqlErrorLogCommand = sqlErrorLogConn.CreateCommand())
      {
        string sqlCommandText = string.Format("INSERT INTO [dbo].[Error_Log] (Description,LoggedAt,ComputerName) VALUES (@Description,@LoggedAt,@ComputerName);");

        sqlErrorLogCommand.CommandText = sqlCommandText;
        sqlErrorLogCommand.Prepare();

        sqlErrorLogCommand.Parameters.AddWithValue("@Description", nErrorMsg);
        sqlErrorLogCommand.Parameters.AddWithValue("@LoggedAt", DateTime.Now);
        sqlErrorLogCommand.Parameters.AddWithValue("@ComputerName", Environment.MachineName);

        sqlErrorLogCommand.ExecuteNonQuery();
      }
    }
  }
  catch (Exception ex)
  {
    MessageBox.Show("There was an error whilst communicating with the database: " + ex.ToString(), "Connection Error", 0, MessageBoxIcon.Error);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM