asp.net-mvc / linq to sql - 我总是需要一个HTML.TextBox来编辑保存吗?

时间:2009-07-22 11:18:19

标签: asp.net-mvc linq-to-sql

我有一个UserController和一个Edit.aspx。有一个字段是我的主键,所以我不想让用户编辑这个字段。

问题是,如果我删除

      <%= Html.TextBox("Email", Model.Email) %>

然后当asp.net-mvc magic调用我的Controller代码时:

 [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, tblMailingList user_)
    {
        try
        {
            repo.UpdateUser(user_);
            return RedirectToAction("Index");
        }
        catch
        {
            return View();

tblMailingList的电子邮件字段为空。问题是我需要这个作为表中的查找来检索当前记录,显然如果它的null我得到一个例外。

当我将文本框放回此字段时,它可以正常工作。我必须有一个文本框并允许编辑将此字段传递给控制器​​,这似乎很疯狂。我尝试将它放在标签中,它仍然在控制器中显示为null。

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

我的第一个问题是你为什么要在电子邮件字段而不是Id字段中进行查找?

您可以将表单声明中的参数传递给Controller。

<% using (Html.BeginForm(
    "MethodName", "Controller", FormMethod.Post, 
    new { id = Model.Id, email = Model.Email)) { %>

我不确定我的方法声明是否正确所以请检查。

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, string email, tblMailingList user_)
{
    try
    {
        repo.UpdateUser(user_);
        return RedirectToAction("Index");
    }
    catch
    {
        return View();

我建议略有不同的更新,因为您的tblMailingList用户无法在您的存储库中更新。

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection form)
{
    tblMailingList user = repo.GetUser(id); // get the user using the id
                                            // so we can update in the same
                                            // context
    UpdateModel(user); // this will automatically update
                       // your user model with values
                       // from the form

    try
    {
        repo.UpdateUser(user);
        return RedirectToAction("Index");
    }
    catch
    {
        return View();

答案 1 :(得分:0)

如果您只想要一个可以传递给控制器​​的字段,该字段需要在表单中不可见,Html.HiddenField可以适用于您的情况。

我错了吗?