MVC5 How to do a post from partialview?

6.7k views Asked by At

My partialview:

@model Alina_2017.Models.DropDownModel

<h2>Groepen</h2>
<div>


    <div>
        @using (Html.BeginForm("SelectGroup", "~/Controllers/WerkvormController"))
        {
            @Html.DropDownListFor(x => x.selectedItem, new SelectList(ViewBag.groepen, "id", "Naam"), "Select", new { @class = "form-control" })
            <input type="submit" id="zoekgroep" value="Zoeken" />
        }
    </div>
</div>

My main view:

@model Alina_2017.Models.WerkvormModel

@{
    ViewBag.Title = "Index";
}

@Html.Partial("~/Views/DropDown/Groepen.cshtml")

//More irrelevant html

My controller:

public ActionResult Index()
{


    ViewBag.groep1 = convertWerkvorm(db.Werkvormens.Where(f => f.GroepenWerkvormID == 1).ToList());
    ViewBag.groep2 = convertWerkvorm(db.Werkvormens.Where(f => f.GroepenWerkvormID == 2).ToList());
    ViewBag.groep3 = convertWerkvorm(db.Werkvormens.Where(f => f.GroepenWerkvormID == 3).ToList());
    setViewBags();
    return View();
}

[HttpPost]
public ActionResult SelectGroup(DropDownModel model)
{
    // the value is received in the controller.
    var selectedItem = model.selectedItem;
    Debug.WriteLine(selectedItem);
    return View("Index");
}

I'm getting a HTTP Error 404.0 - Not Found. Is it possible to call an action from a different controller? The reason it's in a partial view is because I'm using two different models + I'll be using the partialview in multiple other views (at least once I get it to work).

2

There are 2 answers

1
Szörényi Ádám On BEST ANSWER

Your controller's name is wrong.

Replace

@using (Html.BeginForm("SelectGroup", "~/Controllers/WerkvormController"))

with

@using (Html.BeginForm("SelectGroup", "Werkvorm"))

You can verify the actual post URL if you view your source in browser, or check network tab in the browser's development tools.

1
David On

The second argument to the BeginForm() method is simply the name of the controller, not its file:

@using (Html.BeginForm("SelectGroup", "Werkvorm"))
{

}

You can post to any server-side action from anywhere. There's no limit based on how the view is rendered because once everything is rendered it's all just client-side markup no matter where it came from.

As a learning exercise, examine the actual rendered markup in your browser's debugging tools and see the URLs created for the forms. Regardless of how the partial views are arranged, which controller returned the view, what the models are, etc... It's all just HTML in the end. You can even manually write a simple .html file with a form on it which successfully posts to a server-side ASP.NET MVC action.