将数据从模型返回到视图

时间:2013-12-28 07:05:41

标签: asp.net-mvc

现在如何从模型中查看数据? 我的代码:

查看:

 @using (Html.BeginForm("register","Home", FormMethod.Post, new {id="submitForm"})) 
   {

     <div>
      <i>@Html.Label("Name:")</i>
         @Html.TextBox("txtboxName")
     </div>

     <div>
      <i>@Html.Label("Email:")</i>
         @Html.TextBox("txtboxEmail")
     </div>

     <div>  
      <i>@Html.Label("Password:")</i>
         @Html.Password("txtboxPassword")
     </div>

     <div>  
      <button type="submit" id="btnSubmit" name="Command" value="Submit">Submit</button> 
   </div>


}

控制器:

[HttpPost]
        public ActionResult register(string command, FormCollection formData ) 
        {
            if (command == "Submit") 
            {
                var name  = formData["txtboxName"];
                var email = formData["txtboxEmail"];
                var pwd   = formData["txtboxPassword"];

                database db = new database();
                db.connectDB(name, email, pwd);
                ViewBag.Message = email;


            }
            return View();
        }

    }
}

型号:

     namespace LoginSys.Models
    {
        public class database
        {
            public void connectDB(String name, String email, String pwd)
            {
                String conStr = "Data Source=HUNAIN-PC;Initial Catalog=registration;User ID=sa;Password=abc123!@#";

                sqlconnection sqlCon = new sqlconnection(conStr);
                string comm = "insert into tblRegister  values('"+name+"','"+email+"','"+pwd+"')";
                sqlcommand sqlCom = new sqlcom(comm, con);

                try
                {
                 sqlCon.Open();
                 sqlCon.executeNonQuery();
                }
                 catch(exception exc)
                 {
                  //code
                 }
                 finally
                 {
                  con.close();
                 }


            }
        }
    }

现在如何返回由EXECUTENONQUERY声明影响的NO行或假设要返回的任何东西?简单的话,请帮助我这种方法,以后会使用先进的技术。

1 个答案:

答案 0 :(得分:0)

如果要返回某些内容,可以像这样使用SqlParameter ParameterDirection.Output:

SqlCommand cc = new SqlCommand(connStr); // connection string
cc.CommandText = "insert into tblRegister (Name, Email, Pwd) values (@name, @email, @pwd); select @result = @@identity";
cc.AddWithValue("@name", name);
cc.AddWithValue("@email", email);
cc.AddWithValue("@pwd", pwd);
cc.Parameters.Add("@result", SqlDbType.Int);
cc.Parameters["@result"].Direction = ParameterDirection.Output;
cc.ExecuteNonQuery();

// returs identity key
int id = (int)cc.Parameters["@result"].Value;

然后你可以从你的函数返回这个id,但是你必须修改它的原型:

public int connectDB(String name, String email, String pwd) // changed void to int
{
    // ...
    return id;
}

然后您可以将此值简单地添加到ViewBag,或使用其他方式将其传递给您的视图:

            database db = new database();
            ViewBag.Id = db.connectDB(name, email, pwd);
            ViewBag.Message = email;

如果您使用ViewBag,则可以使用@ViewBag.Id

在视图中访问它