简体   繁体   中英

MVC: On button click do some database action and stay on same view

In my view currently I have a form and inside those forms I have three other forms, child form is submitted, i want it to forward some method in controller that just performs some database action but then i want to stay on the same page after the database action is performed.

@using System.Web.Mvc.Html
@using System.Web.UI.WebControls
@using DatePicker.Models.ViewModels.Appointment
@model DatePicker.Models.ViewModels.Appointment.CreateAppointmentSelectPersons
@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
    <link href="~/Content/themes/base/minified/jquery-ui.min.css" rel="stylesheet"/>
}

<h2>Create</h2>
@using(Html.BeginForm("Create","Appointment", FormMethod.Post,new { @class = "form-horizontal", role = "form" }))
{
     @Html.AntiForgeryToken()
    <h4>Step 2</h4>
    <hr />
    @Html.ValidationSummary()

       @*ChildForm1*@
        using (Html.BeginForm("AddAttendeeManual", "Attendee"))
        {
             @Html.HiddenFor(m=>m.SelectedManualEmail.AppointmentId)
            <div class="form-group">
                @Html.LabelFor(m => m.SelectedManualEmail.Email, new { @class = "col-md-2 control-label" })
                <div class="col-md-8 input-group">
                    @Html.TextBoxFor(m => m.SelectedManualEmail.Email, new { id = "Email", @class = "form-control",PlaceHolder="Email"}) <input type='submit' id="btnEmail" class="btn btn-default" value="Add>>" />
                </div>
            </div>
        }


        if (Model.IsSuperOfficeConnected)
        {
           @*ChildFrom2*@
            using (Html.BeginForm("AddAttendeeSuperOffice","Attendee",FormMethod.Post))
            {
                @Html.HiddenFor(m => m.SelectedSuperOfficeEmail.FirstName, new { id = "SelectedSuperOfficeEmail_FirstName" })
                @Html.HiddenFor(m => m.SelectedSuperOfficeEmail.LastName, new { id = "SelectedSuperOfficeEmail_LastName" })
                @Html.HiddenFor(m=>m.SelectedSuperOfficeEmail.AppointmentId)
                @Html.HiddenFor(m => m.SelectedSuperOfficeEmail.SuperOfficePersonId, new { id = "SelectedSuperOfficeEmail_SuperOfficePersonId" })
                <div class="form-group">
                    @Html.LabelFor(m => m.SelectedSuperOfficeEmail.Email, new { @class = "col-md-2 control-label" })
                    <div class="col-md-8 input-group">
                        @Html.TextBoxFor(m => m.SelectedSuperOfficeEmail.Email, new { id = "SelectedSuperOfficeEmail", @class = "form-control", PlaceHolder = "Search in SuperOffice" })

                        <input type='submit' id="btnEmail" class="btn btn-default" value="Add>>" />
                    </div>
                </div>

            }
        }
        if (Model.IsInternalAddressBookEmpty) 
        {
           @*ChildForm3*@
            using (Html.BeginForm("AddAttendeeInternalAddressBook", "Attendee"))
             {
                @Html.HiddenFor(m=>m.SelectedAddressBookPerson.FirstName)
                @Html.HiddenFor(m=>m.SelectedAddressBookPerson.LastName)
                @Html.HiddenFor(m=>m.SelectedAddressBookPerson.AppointmentId)
                 <div class="form-group">
                     @Html.LabelFor(m => m.SelectedAddressBookPerson.Email, new { @class = "col-md-2 control-label" })
                     <div class="col-md-8 input-group">
                         @Html.TextBoxFor(m => m.SelectedAddressBookPerson.Email, new { id = "SelectedAddressBookPerson", @class = "form-control", PlaceHolder = "Search in AddressBook..." }) <input type='button' id="btnAddressBook" class="btn btn-default" value="Add>>">
                     </div>
                 </div>               
             }

        }


       <div class="form-group">
         <div class="col-md-offset-2 col-md-10">
             <input class="btn btn-default" value="<<Previous"/>
             <input type="submit" class="btn btn-default" value="Next>>" />
         </div>
    </div>

}
<style>
    .ui-autocomplete-loading {
        background: url('/Content/themes/base/images/ui-anim_basic_16x16.gif') no-repeat right center;
    }

</style>
@section Scripts{
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/Scripts/jquery-ui-1.10.4.min.js")

    <script type="text/javascript">    
        $(function () {

            $("#SelectedSuperOfficeEmail").
                autocomplete({
                    source: '/Appointment/SuperOfficePerson',
                    minLength: 1,
                    select: function (event, ui) {
                        $('#SelectedSuperOfficeEmail').val(ui.item.value);
                        $(@Html.IdFor(m => m.SelectedSuperOfficeEmail.FirstName)).val(ui.item.FirstName);
                        $(@Html.IdFor(m => m.SelectedSuperOfficeEmail.LastName)).val(ui.item.LastName);
                        $(@Html.IdFor(m => m.SelectedSuperOfficeEmail.SuperOfficePersonId)).val(ui.item.ExternalPersonId);
                    }
            });

            $("#SelectedAddressBookPerson").autocomplete({
                source: '/Appointment/AddressBookPerson',
                minLength: 1,
                select: function(event,ui) {
                    $(@Html.IdFor((m=>m.SelectedAddressBookPerson.FirstName))).val(ui.item.FirstName);
                    $(@Html.IdFor(m=>m.SelectedAddressBookPerson.LastName)).val(ui.item.LastName);
                },
            });

        });
    </script>
}

this is what i've done in controller

[HttpPost]
public void AddAttendeeSuperOffice(CreateAppointmentSelectPersons superOfficePerson)
{
    _attendeeRepository.AddSuperOfficeAttende(superOfficePerson.SelectedSuperOfficeEmail.AppointmentId,
        superOfficePerson.SelectedSuperOfficeEmail.FirstName,
        superOfficePerson.SelectedSuperOfficeEmail.LastName,
        superOfficePerson.SelectedSuperOfficeEmail.Email,
        superOfficePerson.SelectedSuperOfficeEmail.SuperOfficePersonId);

}

[HttpPost]
public void AddAttendeeInternalAddressBook(CreateAppointmentSelectPersons internalAddressbookPerson)
{
    _attendeeRepository.AddInternalAddressBookAttendee(
        internalAddressbookPerson.SelectedAddressBookPerson.AppointmentId,
        internalAddressbookPerson.SelectedAddressBookPerson.FirstName,
        internalAddressbookPerson.SelectedAddressBookPerson.LastName,
        internalAddressbookPerson.SelectedAddressBookPerson.Email);

}

[HttpPost]
public void AddAttendeeManual(CreateAppointmentSelectPersons manualEmail)
{
    _attendeeRepository.AddManualAttendee(manualEmail.SelectedManualEmail.AppointmentId,
        manualEmail.SelectedManualEmail.Email);

}

so whenever my childfrom gets submitted, database action takes place but I get forwarded to different link. I could use, return RedirectToAction but I don't want to load the whole page again, thats makes it kind of slow to load whole thing again.

I thought of using Partial Views but then partial view didn't really help me achieve what I get.

Is there someway to just stay on the same page and make a void call upon child form submission, so that i stay on same page. Maybe, just make the textbox of the child form empty?

It is better to submit child forms to controller using Ajax.

Assuming the below child form you want to submit,

 using (Html.BeginForm("AddAttendeeInternalAddressBook", "Attendee", new{id="frm-child-address"}))

then

$('#mybutton').click(function(){


  var postData=  $('#frm-child-address').serialize();
  $.post('/Attendee/AddAttendeeInternalAddressBook',{data:postData},function(res){
  //based on server response do whatever you require
  });

});

You can use @Ajax.BeginForm and add a javascript callback that would fire off after the controller's action (database call) has completed.

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

@using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST", OnSuccess = "done" }))
{
    @* form *@
}

<script type="text/javascript">
  function done(){
    // The database call is complete.
  }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM