Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with ViewResult and ActionResult containing same parameters

In my controller, I have an Edit GET method to display the view, and an Edit POST method to save the changes:

public ViewResult Edit(int id)
{
    //
}

[HttpPost]
public ActionResult Edit(int id)
{
    //
}

But I'm getting an error saying:

Type 'Controllers.MyController' already defines a member called 'Edit' with the same parameter types

How do I get around this?

like image 425
Steven Avatar asked Dec 21 '22 19:12

Steven


2 Answers

You could implement view models so you have EditViewModel containing all of the fields you wish the user to be able to edit and return this in your Edit GET method and have a strongly typed view to the view model. Then that means that in your POST method you would pass the EditViewModel as a parameter, a bit like this:

[HttpGet]
public ViewResult Edit(int id)
{
    //build and populate view model
    var viewModel = new EditViewModel();
    viewModel.Id = id;
    viewModel.Name = //go off to populate fields

    return View("", viewModel)
}

[HttpPost]
public ActionResult Edit(EditViewModel viewModel)
{
    //use data from viewModel and save in database
}

And so your GET and POST methods would have different signatures. Hope this helps.

like image 63
JayneT Avatar answered Feb 02 '23 06:02

JayneT


You have to read this(3.6 Signatures and overloading) about function overloading.

Function overloading

In this approach you can have two or more functions with same name.But each function must have different signature (i.e. different types of parameter, sequence of parameters or number of parameters).

Note: return type is not a signature of parameter

In your code you have implemented both functions with same name and signatures as well.

like image 34
Javed Akram Avatar answered Feb 02 '23 07:02

Javed Akram