Home > OS >  How to prevent HttpGet method being called?
How to prevent HttpGet method being called?

Time:11-26

So i have a regular method and a HttpGet method:

    //Create a new note
    public ActionResult EditNote()
    {
        return View();
    }

    //Edit a selected note
    [HttpGet]
    public ActionResult EditNote(int id)
    {
        var model = NotesProcessor.LoadNote(id);
        return View(model);
    }

They both use the same views page, but only the HttpGet method will fill up the page with details since the user will be editing an existing note here. So the first method should open up a page that is not filled with data.

My issue is that i don't know how to call the non HttpGet method from my views page since it will automatically call the HttpGet method and the page will give me an error:

The parameters dictionary contains a null entry for parameter 'id'

This is how I'm trying to call the regular method: (Which worked fine before adding the other one)

@Html.ActionLink("Create New", "EditNote")

And this is for the HttpGet method:

@Html.ActionLink("Edit", "EditNote", new { id = Model.Id })

Honestly i thought it would detect the non overloaded syntax and call the right method but it doesn't.

I could make another views page for creating a blank note but that's not very 'DRY'...

What should i do?

CodePudding user response:

You can rename the method with no parameters:

//Create a new note
public ActionResult CreateNote()
{
    return View("EditNote");
}
    
//Edit a selected note
[HttpGet]
public ActionResult EditNote(int id)
{
    var model = NotesProcessor.LoadNote(id);
    return View(model);
}

And then in your view:

@Html.ActionLink("Create New", "CreateNote")
@Html.ActionLink("Create New", "EditNote", new { id = Model.Id })

CodePudding user response:

Try adding HttpGetAttribute with route template without parameters:

[HttpGet("[controller]/[action]")]
public ActionResult EditNote()
{
    return View();
}

But I would argue that it is worth considering renaming EditNode() into CreateNote()

  • Related