我在从表单中获取值并将其传递给控制器时遇到问题。
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(Model)
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
方法。相反,我只想在点击AddUser
按钮时调用form
方法。
2)由于AddUser
被自动调用(第1点),我从u.Username
和u.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中传递的唯一值是Username
和Role
的硬编码值,如上所示,我希望从form
输入值中提取这些值。
答案 0 :(得分:3)
您需要单独的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
}
您还应该考虑添加验证属性(例如[Required]
属性,假设属性的值不能为null
),并在视图中添加验证消息占位符以进行客户端和服务器端验证(参考Introduction to model validation)。
如旁注所示,您的模型描述为单个用户,因此该类应为public class User
(不是复数)
答案 1 :(得分:0)
更改asp-controller =&#34;索引&#34;到asp-controller =&#34; 主页&#34;
答案 2 :(得分:0)
我不知道您是否正在使用临时代码来使控制器正常工作,但不要忘记保护自己免受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项目)
&#34; nErrorMsg&#34;是封装方法的参数:
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);
}