ASP.NET MVC注册警报SQL函数用户存在



我正在ASP.NET MVC中进行注册。我正在使用SQL Server函数来检查是否已经存在具有相同用户名/电子邮件的用户。我不擅长编程,因为也许有一个明显的解决方案,但到目前为止我还没有找到。

我正试图通过控制器或SQL Server函数直接调用警报弹出消息,如"已经有一个用户使用相同的用户名/电子邮件"。

我从SQL Server函数返回了一点,并在控制器中将其转换为布尔值,并试图找到一种方法来提醒消息,方法是将javascript与模型一起使用,或者尝试在View中使用if语句,其中值通过控制器传递。

SQL Server函数代码:

CREATE FUNCTION [dbo].[userExists]
(@email VARCHAR(1024), 
@userName VARCHAR(1024))
RETURNS BIT
AS
BEGIN
IF ((SELECT Email FROM Users WHERE Email = @email) IS NOT NULL)
BEGIN
RETURN 1
END
IF ((SELECT UserName FROM Users WHERE UserName = @userName) IS NOT NULL)
BEGIN
RETURN 1
END
RETURN 0
END

控制器动作代码:

SqlCommand eCmd = new SqlCommand("SELECT dbo.userExists(@email, @userName)", con);
eCmd.Parameters.AddWithValue("email", regModel.Email);
eCmd.Parameters.AddWithValue("userName", regModel.UserName);
bool exists = Convert.ToBoolean(eCmd.ExecuteScalar());
eCmd.Dispose();
if (exists != true)
{
SqlCommand cmd = new SqlCommand("INSERT INTO Users (UserName, Email, Password) VALUES (@userName, @email, @password)", con);
cmd.Parameters.AddWithValue("userName", regModel.UserName);
cmd.Parameters.AddWithValue("email", regModel.Email);
cmd.Parameters.AddWithValue("password", MD5Hash(regModel.Password));
cmd.ExecuteNonQuery();
cmd.Dispose();
}
else
{                                             
return View();
}

到目前为止一切正常。我试图实现的是消息警报,它指示用户是否已经存在。

我试着研究如何使用,尽我所能,使用"return JavaScript("\code\");",但不想工作。

int result=0;
SqlCommand cmd = new SqlCommand("INSERT INTO Users (UserName, Email, Password) VALUES (@userName, @email, @password)", con);
cmd.Parameters.AddWithValue("userName", regModel.UserName);
cmd.Parameters.AddWithValue("email", regModel.Email);
cmd.Parameters.AddWithValue("password", MD5Hash(regModel.Password));
result=cmd.ExecuteNonQuery();
cmd.Dispose();

现在,根据您获得的值,您可以使用jQuery提醒消息。您可以将此值作为Model或以viewBag形式传递。我将尝试使用viewbag作为

ViewBag.resultOfQuery=result;
return View();

从jQuery的前端,您可以将基于@ViewBag.resultOfQuery的警报作为

<script>
function YourFunctionName()
{
if('@ViewBag.resultOfQuery'=="1")
alert("There is already a user with same Username/Email.");
else
alert("Inserted Successfully");
}
</script>

在您的controller方法中,您需要使用ExecuteNonQuery从sql语句中获得一些回报。您必须将您的值存储在从函数获取的某个变量中。


if (exists != true)
{
SqlCommand cmd = new SqlCommand("INSERT INTO Users (UserName, Email, Password) VALUES (@userName, @email, @password)", con);
cmd.Parameters.AddWithValue("userName", regModel.UserName);
cmd.Parameters.AddWithValue("email", regModel.Email);
cmd.Parameters.AddWithValue("password", MD5Hash(regModel.Password));
ViewBag.myval = cmd.ExecuteNonQuery();  // need to use ExecuteNonQuery 
cmd.Dispose();
}
else
{                                             
return View();
}

在视图中,访问您的价值

@Model.myval 

之后,您可以使用javascript来发布您的消息。根据您的产品结构。

最新更新