这是来自我的控制器的动作
[HttpPost]
[AjaxAction]
public ActionResult Registration(RegisterUserModel registerUser)
{
var data;
if (ModelState.IsValid)
{
if (!IsUserExist(registerUser.Email))
{
var crypto = new SimpleCrypto.PBKDF2();
var encrpPass = crypto.Compute(registerUser.Password);
var newUser = _db.Users.Create();
newUser.Name = registerUser.Name;
newUser.Email = registerUser.Email;
newUser.Type = UserType.User.ToString();
newUser.Password = encrpPass;
newUser.PasswordSalt = crypto.Salt;
_db.Users.Add(newUser);
_db.SaveChanges();
data = new { status = "OK", message = "Success" };
}
else
{
data = new { status = "ERROR", message = "User already exists" };
}
}
else
{
data = new { status = "ERROR", message = "Data is incorrect" };
}
return Json(data, JsonRequestBehavior.AllowGet);
}
但我不知道如何以正确的方式初始化data
变量,因为我需要在不同的情况下设置不同的值。这样做的正确方法是什么?
答案 0 :(得分:2)
我通常使用多个return
语句来避免声明像
if(something){
return Json(new{status = "status 1", message = "message1"})
}
else{
return Json(new{status = "status 2", message = "message2"})
}
答案 1 :(得分:2)
以下是其中一个选项
[HttpPost]
[AjaxAction]
public ActionResult Registration(RegisterUserModel registerUser)
{
JsonResult data;
if (ModelState.IsValid)
{
if (!IsUserExist(registerUser.Email))
{
var crypto = new SimpleCrypto.PBKDF2();
var encrpPass = crypto.Compute(registerUser.Password);
var newUser = _db.Users.Create();
newUser.Name = registerUser.Name;
newUser.Email = registerUser.Email;
newUser.Type = UserType.User.ToString();
newUser.Password = encrpPass;
newUser.PasswordSalt = crypto.Salt;
_db.Users.Add(newUser);
_db.SaveChanges();
data = Json(new { status = "OK", message = "Success" }, JsonRequestBehavior.AllowGet);
}
else
{
data = Json(new { status = "ERROR", message = "User already exists"}, JsonRequestBehavior.AllowGet);
}
}
else
{
data = Json(new { status = "ERROR", message = "Data is incorrect" }, JsonRequestBehavior.AllowGet);
}
return data;
}
答案 2 :(得分:1)
你可以试试这个:
var data = new object();
答案 3 :(得分:1)
您可以使用dynamic关键字。
dynamic data;