1

I want to be enable my user to click on an existing entity with, say, Id=123, fetch and copy that object, and then let the user edit it and create a new object using the same view that I'm using to create or edit. I tried the following action method:

    ' GET: /controller/copy/id
    Function Copy(ByVal id As Integer) As ActionResult
        Dim obj = db.MyTable.Find(id)
        If obj.IsNothing() Then
            Return HttpNotFound()
        End If

        'blank out the id to flag that this is a new entity
        obj.Id = 0

        'reuse the editing view
        Return View("Edit", obj)
    End Function

This renders fine, but the form HTML looks like this:

<form action="/Controller/Copy/123" method="post">

And when I post back, the passed model object has Id=123, same as the object being copied. I think this must be because the route /Controller/Copy/123 has the id in the third position, and model binding sees this.

So, how should I implement Copy so that I can copy object 123 but then forget all about that id, to avoid this problem? If there's an entirely different design pattern I should be using, that's fine too.

Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
Joshua Frank
  • 13,120
  • 11
  • 46
  • 95
  • Sounds like you would need to go back to the server when the copy is clicked and recreate the create form but instead this time have the id not be there but the rest of the values are all entered in. – Gjohn Oct 16 '14 at 21:03
  • possible duplicate of [HiddenFor(x => x.Id) is being populated by the UrlParameter instead of the ViewModel](http://stackoverflow.com/questions/8748940/hiddenforx-x-id-is-being-populated-by-the-urlparameter-instead-of-the-viewm) – RubberDuck Sep 01 '15 at 20:22

2 Answers2

0

Override the form action to be "". This means that the current URL will be used.

usr
  • 168,620
  • 35
  • 240
  • 369
0

If i understood you right.... just set id to null or to 0 in form routeValues property

In razor using c#

@using (Html.BeginForm("copy", "controller", FormMethod.Post, new { id = null /* or = 0 */ }))
// form code

In controller:

public ActionResult Copy(int? Id)
// action code
aleha_84
  • 8,309
  • 2
  • 38
  • 46