开发者

ASP.NET MVC 2 edit controller doesn't work using viewmodel

Hey, the problem is that edit controller in ASP.NET MVC 2 doesn't work. I tried many ways and nothing works.

Here's a sample code:

[Authorize]
public ActionResult Edit() {
    var edit = new UserViewModel {
        User = Database.Users.Single(u => u.UserName == User.Identity.Name)
    };

    return View(edit);
}

[Authorize]
[HttpPost]
public ActionResult Edit(FormCollection formCollection) {
    var edit = new UserViewModel {
        User = Database.Users.Single(u => u.UserName == User.Identity.Name)
    };

    // TODO: try, catch
    UpdateModel(edit, "User");
    Database.SaveChanges();

    return View(edit);
}

Here's a view model class:

public class UserViewModel {
    public User User { get; set; }
}

What should I do to update this user model to database? A the moment I'm using only Email field:

<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm()) {%>
<div>
    <div class="UserFieldLeft"><%: Html.LabelFor(model => model开发者_如何学JAVA.User.Email) %></div>
    <div class="UserFieldRight"><%: Html.TextBoxFor(model => model.User.Email, new { style="width: 200px" }) %></div>
    <div class="UserFieldHelper"><%: Html.ValidationMessageFor(model => model.User.Email) %></div>
    <p><input class="UserFieldInput" type="submit" value="Zmień email" /></p>
</div>
<% } %>

If I work on native user model it doesn't work too. What's wrong? Where did I made a mistake?

By the way, I've to use view model to add (in future) some checkboxes (hair color, length, etc.) to my user.

Thank you for your time and help.


You don't need the prefix "User".

UpdateModel(edit);

should work. In the formsCollection their should be a key with User.Email. This should map to the Email property in the User Object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜