MVC5 Details/Edit/Delete with Multi-Key Table

522 Views Asked by At

Pretty new to MVC5 but gaining ground quickly. This small issue has me stumped and there does not seem to be much information on Goolge (or I am not asking Google the right questions).

I have a Table (FILE_RCPTS_LOG) This table has multi keys (2)
First Key is Field: TRACK_NMBR (int) Second Key is Field: TRANS_DT (date)

When I created my Controller, the default views were also created. And for the most part, they work fine. However, I am getting HttpNotFound Errors, when attempting to use the Edit\Delete\Details links

@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ }
@Html.ActionLink("Details", "Details", new {/* id=item.PrimaryKey */ }) 

This would be fine, if my table only had one key. But how do I pass both keys?

The few solutions I found online seemed way to complicated for such a simple action. I think I am missing something obvious here . . .

This is the code for my controller (Details)

  public async Task<ActionResult> Details(int? id, DateTime id2)
    {

        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        FILE_RCPTS_LOG fILE_RCPTS_LOG = await db.FILE_RCPTS_LOG.FindAsync(id);
        if (fILE_RCPTS_LOG == null)
        {
            return HttpNotFound();
        }
        return View(fILE_RCPTS_LOG);
    }

I have tried several ways of passing multiple keys, but nothing is working. I have read a few tutorials about using SPLIT but I could not get that working either. This seems like such a simple and very common thing, as I would think most tables have multi-keys.

Is there a simple way of doing this that I am not seeing? I feel like I am over-thinking it.

thanks!!!

2

There are 2 best solutions below

8
On BEST ANSWER

You can follow this. The first, in ActionLink, pass all 2 key values in as a comma delimited string. For example in Detail action:

@Html.ActionLink("Details", "Details", new {id= @item.TRACK_NMBR +','[email protected]_DT});

In Details ActionController, you need to parse each of the 2 keys out.

string[] splitid = id.Split(',');
            FILE_RCPTS_LOG obj = db.FILE_RCPTS_LOG.Find(Convert.ToInt32(splitid[0]),Convert.ToDateTime(splitid[1]));

Or you can transfer 2 params as your solution:

@Html.ActionLink("Details", "Details", new {id= @item.TRACK_NMBR, id2 [email protected]_DT});

public async Task<ActionResult> Details(int? id, DateTime id2)
{
FILE_RCPTS_LOG obj = db.FILE_RCPTS_LOG.Find(id, id2);
}

Remember the order of the keys is important. Hope to help, my friend!

1
On

Assuming that you are passing the view a model, just return the model in the action link. then you will have everything you need to know, including both Primary keys.