0

This is my controller code. I have one view and inside that i have one partial view. At the end in partial view i have one submit button. When i click this button i want to save data of main view and partial view to thier respective tables.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;
using System.Data.Entity.Validation;

namespace MvcApplication2.Controllers
{
    public class HomePageController : Controller
    {
        //
        // GET: /HomePage/
        MVCDemoEntities db = new MVCDemoEntities();
        public ActionResult Submit()
        {
            List<DocTypeMaster> alldoclist = new List<DocTypeMaster>();
            using (MVCDemoEntities db = new MVCDemoEntities())
            {
                alldoclist = db.DocTypeMasters.OrderBy(a => a.DocTypeName).ToList();
            }
            ViewBag.docid = new SelectList(alldoclist, "Id", "DocTypeName");
            return View();

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Submit(DetailsEntry de)
        {
            List<DocTypeMaster> alldoclist = new List<DocTypeMaster>();
            using (MVCDemoEntities db = new MVCDemoEntities())
            {
                alldoclist = db.DocTypeMasters.OrderBy(a => a.DocTypeName).ToList();
            }

            ViewBag.docid = new SelectList(alldoclist, "Id", "DocTypeName", de.DocumentId);



                       return View(de);
        }



        [HttpGet]
        public PartialViewResult RacersByCountryPartial(string id)
        {
            Passport ps = new Passport();
            Pan pn = new Pan();
            string id1 = id.Trim();
            if (id1 == "Passport")
                return PartialView("~/Views/HomePage/id1.cshtml", ps);
            else
                return PartialView("~/Views/HomePage/pancard.cshtml", pn);


        }   
        [HttpPost]
        public ActionResult RacersByCountryPartial(string id,Passport ps, Pan pn,DetailsEntry dt)
        {

            return View(id);
        }
    }


}

this is my Mainview.

@model MvcApplication2.DetailsEntry

@{
    ViewBag.Title = "Submit";
}

<h2>Submit</h2>

@using (Html.BeginForm("Submit", "HomePage", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>DetailsEntry</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.ClientId)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ClientId)
            @Html.ValidationMessageFor(model => model.ClientId)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ClientName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ClientName)
            @Html.ValidationMessageFor(model => model.ClientName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.EmployeeId)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EmployeeId)
            @Html.ValidationMessageFor(model => model.EmployeeId)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.EmpCitizenId)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EmpCitizenId)
            @Html.ValidationMessageFor(model => model.EmpCitizenId)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.EmpName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.EmpName)
            @Html.ValidationMessageFor(model => model.EmpName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Nationality)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Nationality)
            @Html.ValidationMessageFor(model => model.Nationality)
        </div>

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

           @Html.DropDownListFor(Model => Model.DocumentId, @ViewBag.docid as SelectList,"Select document Type")
            @Html.ValidationMessageFor(Model=>Model.DocumentId)
            </div>


    </fieldset>
}
<div id="container"> </div>
<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="//code.jquery.com/jquery-1.11.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#DocumentId").change(function () {
            $("#log").ajaxError(function (event, jqxhr, settings, exception) {
                alert(exception);
            });

            var countrySelected = $("select option:selected").first().text();

            $.get('@Url.Action("RacersByCountryPartial")',
                              { id: countrySelected }, function (data) {

                    $("#container").html(data);
                });
        });
    });
</script>

This is my partial view.

@model MvcApplication2.Passport

<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Passport</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.pissueddate)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.pissueddate)
            @Html.ValidationMessageFor(model => model.pissueddate)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.pissuedlocation)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.pissuedlocation)
            @Html.ValidationMessageFor(model => model.pissuedlocation)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.pimage)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.pimage)
            @Html.ValidationMessageFor(model => model.pimage)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

There is one submit button at the end of partial view. I want to save both main view and partial view data on single button click to respective tables. Please advise me.

tmg
  • 19,895
  • 5
  • 72
  • 76
Niranjan godbole
  • 721
  • 3
  • 13
  • 28
  • I dint stuck. [HttpPost] What logic I have to write inside the public ActionResult RacersByCountryPartial(string id,Passport ps, Pan pn,DetailsEntry dt) method? – Niranjan godbole Jan 11 '16 at 12:26
  • Put `
    ` inside your `Html.BeginForm()`, so that when partial view renders, and you click on submit button, form will be posted.
    – ramiramilu Jan 11 '16 at 12:26
  • I left RacersByCountryPartial action method blank. I want to write here code to save data of main view and partial view to database. – Niranjan godbole Jan 11 '16 at 12:27
  • Check this tutorial - http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/implementing-basic-crud-functionality-with-the-entity-framework-in-asp-net-mvc-application. You will get to know how to save data using entity framework. – ramiramilu Jan 11 '16 at 12:28
  • Here i am able to save partial view data to db. But mainview data i am not able to save. – Niranjan godbole Jan 11 '16 at 12:28
  • I know the method to save data to db. inside RacersByCountryPartial action method how can i save mainview data? – Niranjan godbole Jan 11 '16 at 12:30
  • $('#btnSubmitID').click(function(){ $('form').submit(); }); if you have two different forms – Anil Panwar Jan 11 '16 at 12:31
  • I am new to mvc. Can you tell me in more details. should i use jquery inside the partial view? – Niranjan godbole Jan 11 '16 at 12:34
  • You are doing it fine,let me know if you are using the two different form action in both main and partial views? – Anil Panwar Jan 11 '16 at 12:35
  • There is no need to use JQuery. All you need to do is to construct the Partial view elements `name` to be inline with the main object. And then just put the Put `
    ` inside your `Html.BeginForm()`, so that when you click on submit button, entire form (Main View data + Partial view data) will be posted to action. On the Action, expect the ENTIRE object which is combination of Main object + Partial View Object.
    – ramiramilu Jan 11 '16 at 12:37
  • I am able to save partial view data as below. public ActionResult RacersByCountryPartial(string id,Passport ps, Pan pn,DetailsEntry dt) { if (ModelState.IsValid) { db.Passports.Add(ps); db.SaveChanges(); } return View(id); } Same way I want to save main view data in this block. – Niranjan godbole Jan 11 '16 at 12:39
  • Anil, I am using two different action methods for my views. – Niranjan godbole Jan 11 '16 at 12:40
  • Hi Ramiramilu, How can put my div inside the html.beginform()? – Niranjan godbole Jan 11 '16 at 12:42
  • Okie, so you just have to put hidden submit button in the main form for and give id to submit button of the partial view, on click of the submit button of the partial button, submit both form as $('#PartialSubmitBtnID').click(function(){ $('#form1 #form2').submit(); }); – Anil Panwar Jan 11 '16 at 12:43
  • $('#PartialSubmitBtnID').click(function(){ $('#form1 #form2').submit(); }); This jquery code i have to write in main view or partial view? and how $('#form1 #form2').submit(); implementation will work? – Niranjan godbole Jan 11 '16 at 12:49
  • As per my knowledge i want to get main model in child model I am not sure – Niranjan godbole Jan 11 '16 at 13:24

1 Answers1

0

So, if I understand correctly what you're trying to achieve...

  1. Remove the submit button from the partial view and move it to the main view
  2. Remove the form from the partial view and let the main form to handle a whole user's input - in your case you have two forms, that means each form should submit its own data to the respective controller/action. Nesting of html forms is impossible - Can you nest html forms?

If you need to do some actions (like showing dynamic dropdowns with loading of different data or something else) - do that as separate AJAX calls inside the partial view. But the main form, that finally submits data, should be the only one.

Community
  • 1
  • 1
drcolombo
  • 194
  • 6
  • Welcome to StackOverflow! You could actually add some (pseudo-)code to demonstrate your approach. – jkalden Jan 11 '16 at 12:47
  • Yes exactly. I am using different models for main view and partial views. – Niranjan godbole Jan 11 '16 at 12:50
  • Well, from your question it's unclear, what the domain structure is, how your main and partial view models are interacting to each other. But a general answer - if you put your child model (the one used for the partial view) as a member of the main model, then the Submit action of the controller will get all the necessary data in one place. – drcolombo Jan 11 '16 at 13:09
  • I have sepearate model for main view and partial view. I main model i have drop down when the dropdown selected index changed, using jquey i am calling that perticular partial view. Till this point there is no intereaction between models. – Niranjan godbole Jan 11 '16 at 13:30
  • $.get('@Url.Action("RacersByCountryPartial")', { id: countrySelected }, function (data) { $("#container").html(data); }); }); Here i am calling partial view. public PartialViewResult RacersByCountryPartial(string id) { Passport ps = new Passport(); Pan pn = new Pan(); string id1 = id.Trim(); if (id1 == "Passport") return PartialView("~/Views/HomePage/id1.cshtml", ps); else return PartialView("~/Views/HomePage/pancard.cshtml", pn); – Niranjan godbole Jan 11 '16 at 13:34
  • I meant, if you make the Passport as a member of DetailsEntry and then do what I wrote above in the answer, the POST Submit action will receive a whole DetailsEntry that will contain the Passport as well. So everything will work like a charm :) – drcolombo Jan 11 '16 at 13:38
  • Basically, your partial view does only one thing - showing/modifying of Passport. And as it's a **partial** view, that means it's a **part** of something big. In this case this **big** should take care of data manipulation. For me it looks you're trying to make things more complex than they are. Partial views are purposed to show something repeatable, that can be shown in different places (different forms, different places of different pages, etc.) in order to avoid repeating the code in these many places. – drcolombo Jan 11 '16 at 13:45
  • But the problem with forms is they cannot be nested. If for some reason you need to post more than one form with the only click from the user's side, you should write some JavaScript code that will submit the second (all other forms) one by one or asynchronously without forcing a user to do more than one click. The question is why do you need to submit more than one form... – drcolombo Jan 11 '16 at 13:45
  • Tables are sepearate so when i click on submit button i want to save datato both tables. – Niranjan godbole Jan 11 '16 at 16:04
  • So is there any other way to display partial view below when selectedindexof dropdown changes? – Niranjan godbole Jan 11 '16 at 16:05
  • How can i make passport as member of details entry? I am new to mvc so things are going complicated. Thanks for your well responce. – Niranjan godbole Jan 11 '16 at 16:08
  • I put everything in one model and with the help of jquery and div tag i achieved this task. but my boss dont need in this way. They told to use seperate models. So i am trying in this way – Niranjan godbole Jan 11 '16 at 16:41
  • But the Passport will be still a separate model (or saying differently - it can be still used as a separate object), why not? Moreover - you can still keep it as @model Passport in the partial view. The only thing is to remove the nested form and create a property in the DetailsEntry class of the Passport type. That's it. So, you will have two models (two classes) and one of them will just have another as a member (a reference in terms of database). – drcolombo Jan 12 '16 at 19:45