djmarquette
djmarquette

Reputation: 822

Override of Create() ActionResult?

I am working on my "first" MVC 3 application and am stumped by the following issue. Basically I have a Contact form that gathers input and saves to the db. On a page listing all Contact submissions, I want the user (this will be Admin role in the future) to be able to select a single Contact from the Contact list page and click "Make Client" to call my ClientController and convert this Contact into a Client. The ClientController page also has a Create() method to enter a new Client record from scratch, so to avoid complexity in that method, I am attempting to create a "Make" action that accepts a contactID as a parameter.

I have the following code on the Contact List page:

@Html.ActionLink("Make Client", "Make", "Client", new { id = item.ID }, null)

With the client controller appearing as thus:

    [HttpGet]
    public ActionResult Create()
    {
        return View(new Client());
    }

    //
    // GET: /Make
    //  used for converting a Contact record into a Client
    [HttpGet]
    public ActionResult Make(int contactID)
    {
        try
        {
            var contactModel = _db.Contacts.Single(r => r.ID == contactID);

            var clientModel = new Client()
            {
                FirstName = contactModel.FirstName,
                LastName = contactModel.LastName,
                <snip> . . . ,
                ZipCode = contactModel.ZipCode
            };

            return View(new Client(clientModel));
        }
        catch (Exception ex)
        {

            base.ViewData["Exception"] = "Exception: " + ex.InnerException.ToString();
            throw;
        }
    }

The problem is that the contactID received in Make(int contactID) is always null. I have been able to tweak some things to get the following to work by calling the standard Create() ActionResult with a nullable int parameter, but this feels hokey:

    [HttpGet]
    public ActionResult Create(int? id)
    {
        if (id == null)
        {
            return View(new Client());
        }
        else
        {
            return (Make(id));
        }
    }

The bottom line is that I can call this Create() ActionResult the parameter is not null, but when I call Make() directly, the parameter is not passed along. Is there something special about Create() that makes this work?

Thanks, and I am open to other alternatives as well.

Upvotes: 0

Views: 922

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

The action argument of the Make action is called contactID, so when generating the link to this action use this name:

@Html.ActionLink(
    "Make Client", 
    "Make", 
    "Client", 
    new { contactid = item.ID }, 
    null
)

This will successfully pass the correct value as argument when invoking the Make action. So you no longer need the tweak in the Create action.

Upvotes: 3

Related Questions