Submit Data from partial view to a controller MVC

collect form data from both main and partial view in mvc
pass data from partial view to controller
submit partial view mvc 5
partial view submit button not working
mvc submit only partial view
partial view controller
how to bind data to partial view in mvc
html.beginform partial view

I have a list of employment records, you can also add an employment record from the same page using a partial view.

Heres employment.cshtml that has a partial view for the records list and a partial view to add a new record which appears in a modal pop up.

<h2>Employment Records</h2>

  @{Html.RenderPartial("_employmentlist", Model);}                              

<p>
<a href="#regModal" class="btn btn_b" rel="fancyReg">Add New Record</a>
</p>

<div style="display:none">
    <div id="regModal"> 
              @{Html.RenderPartial("_AddEmployment", new ViewModelEmploymentRecord());}     

                        </div>
                    </div>

Heres the partial view _AddEmployment.cshtml

@using (Html.BeginForm("AddEmployment, Application"))
{                   
@Html.ValidationSummary(true)

<div class="formEl_a">

<fieldset>
    <legend></legend>

     <div class="sepH_b">

            <div class="editor-label">
                @Html.LabelFor(model => model.employerName)
            </div>

         etc....etc....

</fieldset>

</div>
  <p>
        <input type="submit" class="btn btn_d" value="Add New Record" />

    </p>


}

and heres my Application controller:

[HttpPost]
    public ActionResult AddEmployment(ViewModelEmploymentRecord model)
    {
        try
        {
            if (ModelState.IsValid)
            {

                Add Data.....
            }
        }
        catch
        {

        }

        return View(model);
    }

When compiling the following html is generated for the form:

<form action="/Application/Employment?Length=26" method="post"> 

It brings in a length string? and is invoking the Employment controller instead?

Hope all is clear....

QUESTION ONE: when I click the submit button from within the partial view it does not go to the controller specified to add the data. Can anyone see where im going wrong?

QUESTION TWO: When I get this working I would like to update the employment list with the new record....am I going about this the correct way? Any tips appreciated.

Answer 1: First try this and let me know if that hits your controller.

 @using (Html.BeginForm("AddEmployment", "Application", FormMethod.Post))

Answer 2: To update the employment list, I would assume you would want to save the model to your database then have your employment list displayed on the same page or a different page calling the data from the DB into the the list or table to be displayed.

Edit: It looks as though your form attributes are not being applied. For your employment.cshtml, I personally don't use { } around my @Html statements. You must not be doing what I stated above because your error occurs only when I write it as

 @using (Html.BeginForm("AddEmployment, Application", FormMethod.Post))

missing those closing quotes is what is causing your problem.

Sending data from Partial View to View, I have a principal View with Model MatchModel public class Mvc.Html; I think I have to load on partial view controller, but I'm not sure. Html.BeginForm does not support PartialViews and will allways update the whole view with the content of the partial view. Use Ajax.BeginForm to achieve update of the partial view. Pass new AjaxOptions {updateTargetId='_partial' along with the call to specify the placeholder for the partial view. In your case:

jQuery code:

window.jQuery(document).ready(function () {
    $('#btnsave').click(function () {

        var frm = $("form");
        var data = new FormData($("form")[0]);
        debugger;
        $.ajax({
            url: '/Home/Update',
            type: "POST",
            processData: false,
            data: data,
            dataType: 'json',
            contentType: false,
            success: function (response) {
                alert(response);
            },
            error: function (er) { }
        });
        return false;
    });

});

Controller Code

[HttpPost]
    public JsonResult Update(Generation obj)
    {
        if (ModelState.IsValid)
        {
            return Json("done");
        }
        else
        {
            return Json("error create");
        }
    }

Using those code you can post form using jquery and get response in jsonresult

Collect Form Data From Both Main and Partial View in MVC, Add one controller And the main view will contain one partial view. After clicking on the submit button in the main view, the data will be bound to the person class and it will pass to the GetPerson() action. And the main view will contain one partial view. public class personController: Controller { public ActionResult Index() { return View(); } public void GetPerson(person p) { }} After clicking on the submit button in the main view, the data will be bound to the person class and it will pass to the GetPerson() action. Fine, now we will add two

you have put @using (Html.BeginForm("AddEmployment, Application")) what this is trying to do is invoke a action called "AddEmployment, Application" i think you meant @using (Html.BeginForm("AddEmployment", "Application"))

Passing Data To Partial Views That Submit In ASP.NET MVC 2 , Basically, I had a strongly-typed partial view that submitted data. In addition to consuming, validating, and transmitting its model to the controller� Compile your project (Shift+Ctrl+B), right click ClientInfo in Home Controller and Add View. Check Create a strongly-type view, choose ClientVM and scaffold template : Edit. Right click on shared folder add view and call it _Address.

I know this is very old Question the reason it didn't work for you because your syntax Here is your code

@using (Html.BeginForm("AddEmployment, Application"))

the fix

@using (Html.BeginForm("AddEmployment", "Application"))

Regards

How do I submit data from a partial view in MVC4?, Can you please try by specifying the action and controller explicitly in Html. BeginForm like below. Hide Copy Code. @using� A partial view is a Razor markup file (.cshtml) that renders HTML output within another markup file.Partial view is not a complete view. Partial view is used for reusability of the HTML markup.

Partial View in ASP.NET MVC, If a partial view will be shared with multiple views of different controller folder then model object and View data passes view data dictionary to the partial view. Data flow is only Page Controller => Partial Controller. To be closer to WebForm UserControl (*.ascx) you need to: Create a page Model and a Partial Model. Place your Partial Model as a property in your page Model. In page's View use Html.EditorFor(m => m.MyPartialModel) Create an appropriate Partial View

ASP.NET MVC, By decoupling the presentational layer from the data exchange layer, AJAX (or NET MVC components like controller actions and partial views. Because the submit button is associated with the HTML form defined in this� Mine Question is if doing like this, the Index of HTTPPOST of main view will fire first. than follow by Partial view A and Partial View B. In this case I need to store the data in HttpContext.Items and call the submit to Database in the last Partial view B. What I want is fire the Partial view A and B first, and store the data into Main View's

ASP.NET MVC Partial Views and Forms, In MVC, there is this cool concept of a partial view. Let's say you have two forms on one page, and you want to submit each one separately. The basic change is to modify our controller actions to return a Partial View: From there we can actually perform validation that only relates to that particular data. Load ASP.NET MVC Partial Views Dynamically Using jQuery: Model Binding to List of Objects in ASP.NET MVC: Perform List, Insert, Update and Delete in a Single View in ASP.NET MVC: Four Ways of Handling Multiple Submit Buttons in ASP.NET MVC: Generating Short URLs using Google URL Shortener API: Passing data from one controller to another in ASP

Comments
  • to question one: if you put something in your catch block in your app. controller, would that provide some insight?
  • 1) At the point of using magic strings, I would stop using Html.BeginForm and just write the <form> tag myself manually. Try that first and see if you can post to your action method. 2) Assuming you mean checking the ModelState.IsValid flag? That's only really going to be useful if you're using DataAnnotations.
  • When I compile the page the form tag generates ok <form action="/Application/Employment?Length=26" method="post">. It seems to be going to the wrong controller however, employment instead of addEmployment?? Ive updated the main post with this info
  • On a side note. I would not use try catch in a general scenario. Only catch errors you know might happen. then specify it as much as possible. Such as null exception. tho that is a pretty general exception type. If you are worried about uncaught exceptions the best way to deal with these is putting something like ELMAH in place on your site to catch and log these errors.
  • It wont let me add the form method....I get the following error: ****Error 'System.Web.Mvc.HtmlHelper<ViewModels.ViewModelEmploymentRecord>' does not contain a definition for 'BeginForm' and the best extension method overload 'System.Web.Mvc.Html.FormExtensions.BeginForm(System.Web.Mvc.HtmlHelper, string, string)' has some invalid arguments Views\Application_AddEmployment.cshtml ***
  • Please change this code: ("AddEmployment, Application", FormMethod.Post) to this: ("AddEmployment", "Application", FormMethod.Post) and you will no longer run into the error and your form should post to the correct controller. Best Regards
  • ARRRRRRRRGGGGHHH!! Of course! Thanks for the help guys, hitting the controller and saving now. Now to get in to refresh the view without the postback!
  • Im trying to invoke the AddEmployment action in the Application Controller. The second part of your answer is the same as what I have?
  • Im just seein its not the same after reading the other answer..thanks!
  • @Dez79 I was showing you haven't closed the quotes so its just reading as action not as 2 parameters action and controller