ASP.NET MVC 4 Submit from 2 partials on same view invokes both action methods for each submit

StackOverflow https://stackoverflow.com/questions/21965824

  •  15-10-2022
  •  | 
  •  

Question

I am brand new to .NET MVC Programming - and have been stuck here with no where to go:

2 Models representing 2 tables in a db

 public class t1
{
    public string c1 { get; set; }
    public string c2 { get; set; } ...

2 partial views one for each model

@model WebApplication2.Models.Database.t1
@using (Ajax.BeginForm( new AjaxOptions { UpdateTargetId = "t1div" }))
{
<fieldset>
     @Html.EditorFor(model => model.c1)
     <input type="submit" value="t1view" class="btn btn-default" />
 ....

@model WebApplication2.Models.Database.t2
@using (Ajax.BeginForm( new AjaxOptions { UpdateTargetId = "t2div" }))
{
<fieldset>
     @Html.EditorFor(model => model.c4)
     <input type="submit" value="t2view" class="btn btn-default" />
 ....

1 "composite" controller with actions to process submits from both partial views

public ActionResult t1view()
    {
        t1 model = new t1();....
    }
 [HttpPost]
 public ActionResult t1view([Bind(Include = "c1,c2,c3")] t1 t1)
    {
        if (ModelState.IsValid)....
    }
public ActionResult t2view()
    {
        t2 model = new t2();....
    }
 [HttpPost]
 public ActionResult t2view([Bind(Include = "c4,c5,c6")] t2 t2)
    {
        if (ModelState.IsValid)....
    }

and the index view

<div id="t1div">
   @Html.Action("t1view")
</div>
   <br />
<div id="t2div">
   @Html.Action("t2view")
</div>

So the "composite" view with the 2 partial views displays data from the tables okay. When I make some changes and hit either of the buttons, even though I have specifically called the correct action method, both the action methods under [HttpPost] get called all the time, and one of the fails as that particular partialview just sent null for the "other" table. Any ideas what am I doing wrong here? Its just been a week of me learning this - what am I doing wrong here?

Was it helpful?

Solution

explicitly you have to give action property in ajax.beginForm for which action you are going to make request

@model WebApplication2.Models.Database.t1
@using (Ajax.BeginForm("t1view","controllerName", new AjaxOptions { UpdateTargetId =       "t1div" }))
{
<fieldset>
 @Html.EditorFor(model => model.c1)
 <input type="submit" value="t1view" class="btn btn-default" />
 ....

@model WebApplication2.Models.Database.t2
@using (Ajax.BeginForm("t2view","controllerName", new AjaxOptions { UpdateTargetId = "t2div" }))
{
<fieldset>
 @Html.EditorFor(model => model.c4)
 <input type="submit" value="t2view" class="btn btn-default" />
....
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top