Toby Caulk
Toby Caulk

Reputation: 276

POST data to controller with ASP.NET MVC

I am using ASP.NET MVC with C# and pure bootstrap. One of my views contains a label, text input box, and a submit button:

@{
   ViewBag.Title = "BinSearch";
   Layout = "~/Views/Shared/_LayoutSearch.cshtml";
}

<h2>BinConfig Search</h2>

@using (Html.BeginForm("FiEdit", "EditConfigController"))
{
    <div class="form-group">
        <label for="issuerKey">Issuer Key</label>
        <input type="text" name="key" />
        <input type="submit" class="btn btn-default" value="Search" />
    </div>
}

When I click the "submit" button, I would like to transfer the data to a controller, EditConfigController to this method:

[HttpPost]
public ActionResult FiEdit(int key)
{
    return View(new IssuerKey().Key = key);
}

Which then is supposed to create a new view where I can edit data based off the key provided. This is the FiEdit view:

@model BinFiClient.Models.IssuerKey

@{
    ViewBag.Title = "FiEdit";
    Layout = "~/Views/Shared/_LayoutEdit.cshtml";
}

<h2>FiEdit</h2>

However, when I click the "submit" button, I receive a 404 error, and the URL path looks like this:

http://localhost:58725/EditConfigController/FiEdit

Which is actually the path to the method in the controller that I posted above.

What I need is basically a way to POST data to another controller. How can I accomplish this?

Edit: Now I am receiving the error:

The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'BinFiClient.Models.IssuerKey'.

Upvotes: 2

Views: 31579

Answers (2)

johnnyRose
johnnyRose

Reputation: 7490

Try replacing your code with the following:

@using (Html.BeginForm("FiEdit", "EditConfig", FormMethod.Post))
{
    <div class="form-group">
        <label for="issuerKey">Issuer Key</label>
        <input type="text" name="key" />
        <input type="submit" class="btn btn-default" value="Search" />
    </div>
}

This will POST the parameter key to the EditConfig controller.

If you'd like to post to the action TestEdit in another controller, say the TestController, your code should be changed to the following:

@using (Html.BeginForm("TestEdit", "Test", FormMethod.Post))
...

To resolve the "model item passed into the dictionary" error, change your POST to be this:

[HttpPost]
public ActionResult FiEdit(int key)
{
    return View(new IssuerKey() { Key = key });
}

Upvotes: 2

Benjamin RD
Benjamin RD

Reputation: 12034

ou can try with:

    @using (Html.BeginForm(("FiEdit", "EditConfigController", FormMethod.Post,
                new { enctype = "multipart/form-data" })))
{
    <div class="form-group">
        <label for="issuerKey">Issuer Key</label>
        <input type="text" name="key" />
        <input type="submit" class="btn btn-default" value="Search" />
    </div>
}

Upvotes: 1

Related Questions