views:

138

answers:

2

I have a UserController and an Edit.aspx. There is one field that is my primary key so i dont want to allow users to edit this field.

The issue is that if i remove the

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

then when the asp.net-mvc magic calls my Controller code:

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

the email field of the tblMailingList is null. The issue is that i need this as the lookup in the table to retrieve the current record and obviously if its null i get an exception.

When i put the textbox back for this field, it works fine. It seems crazy that i would have to have a textbox and allow editing to pass this field over to the controller. i tried putting it in a label and it still shows up as null in the controller.

any suggestions?

A: 

If you just want a field that could passed to controller which needs to be invisible in the form, Html.HiddenField could work for your case.

Do I get wrong?

yapiskan
+3  A: 

My first question would be why are you doing the lookup on the Email field and not the Id field?

You can pass parameters in your Form declaration to be passed through to your Controller.

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

I'm not sure if I got the method declaration correct so please check.

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

I would recommend updating slightly differently as your tblMailingList user will not be valid to be updated in your Repository.

[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();
David Liddle