Repopulate Textbox in PartialView When Page Fails Validation - asp.net-core-mvc

I have a View that besides being bound to a model, has 3 partial views (a people picker) of a reuseable component. I perform a validation to check for duplicates of the data in the model at submit. If the record is a dup, it redirects back to the page, where the model can repopulate the model fields. However, I'd like the People Picker values to be retained as well, but since it is not part of the model, I don't know how to do that.
This is the controller
public ActionResult Create(IFormCollection collection)
{
try
{
Dept_COEModel Dept = new DeptModel();
Dept.DeptName = collection["DeptName"];
Dept.DeptAcronym = collection["DeptAcronym"];
Dept.DeptCeNtId = collection["UserIdHidden_20"];
Dept.DeptCeUserName = collection["UserNameHidden_20"];
Dept.DeptCeEmail = collection["UserEmailHidden_20"];
Dept.delegate1PocNtId = collection["UserIdHidden_30"];
Dept.delegate1PocName = collection["UserNameHidden_30"];
Dept.delegate1PocEmail = collection["UserEmailHidden_30"];
Dept.delegate2PocNtId = collection["UserIdHidden_40"];
Dept.delegate2PocName = collection["UserNameHidden_40"];
Dept.delegate2PocEmail = collection["UserEmailHidden_40"];
int result = _adoSqlService.CheckDept(collection["DeptName"]);
if (result == 0)
{
_adoSqlService.InsertDept(dept);
return RedirectToAction(nameof(Index));
}
else
{
ModelState.AddModelError("DeptName", "This Department already exists");
ViewData["UserResultTextbox_20"] = Dept.DeptCeUserName;
return View(Dept);
}
}
catch
{
return View(Dept);
}
}
Here is the View
#model EDAD.Models.LOB_COEModel
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>LOB_COE</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
#*<div class="form-group">
<label asp-for="lobCoeId" class="control-label"></label>
<input asp-for="lobCoeId" class="form-control" />
<span asp-validation-for="lobCoeId" class="text-danger"></span>
</div>*#
<div class="form-group">
<label asp-for="lobCoeName" class="control-label"></label>
<input asp-for="lobCoeName" class="form-control" />
<span asp-validation-for="lobCoeName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="lobCoeAcronym" class="control-label"></label>
<input asp-for="lobCoeAcronym" class="form-control" />
<span asp-validation-for="lobCoeAcronym" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Select Chief Engineer</label>
<div class="form-group form-field-div">
<table>
<tr style="white-space:nowrap;">
<td>
#Html.Action("PeoplePicker", "PeoplePicker", new EDAD.Models.PeoplePickerViewModel { PickerId = 20 })
</td>
<td></td>
</tr>
</table>
</div>
#*<span asp-validation-for="lobCoeCeNtId" class="text-danger"></span>*#
</div>
<div class="form-group">
<label class="control-label">Select Delegate 1</label>
<div class="form-group form-field-div">
<table>
<tr style="white-space:nowrap;">
<td>
#Html.Action("PeoplePicker", "PeoplePicker", new EDAD.Models.PeoplePickerViewModel { PickerId = 30 })
</td>
<td></td>
</tr>
</table>
</div>
#*<span asp-validation-for="lobCoeCeNtId" class="text-danger"></span>*#
</div>
<div class="form-group">
<label class="control-label">Select Delegate 2</label>
<div class="form-group form-field-div">
<table>
<tr style="white-space:nowrap;">
<td>
#Html.Action("PeoplePicker", "PeoplePicker", new EDAD.Models.PeoplePickerViewModel { PickerId = 40 })
</td>
<td></td>
</tr>
</table>
</div>
#*<span asp-validation-for="lobCoeCeNtId" class="text-danger"></span>*#
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Here is the cshmtl for the People Picker (note that this is reusable so I don't want to modify any code in this)
#model ABC.Models.PeoplePickerViewModel
<script src="~/lib/jquery/jquery.js"></script>
<script src="~/js/site.js"></script>
<script>
$(function () {
setUpGlyphicons(#Model.PickerId, '#Url.Action("SearchForUsers", "PeoplePicker")');
});
</script>
<div class="people-picker">
#Html.TextBox("UserResultTextbox_" + Model.PickerId, Model.User.userName, new { #onkeypress = "userSearchKeyPress(event);", #class = "form-control input-smaller", style = "display: inline", placeholder = "Last Name, First Name", autocomplete = "off" })
#Html.Hidden("UserIdHidden_" + Model.PickerId, Model.User.NTId)
#Html.Hidden("StoredUserNameHidden_" + Model.PickerId, Model.User.userName)
#Html.Hidden("UserNameHidden_" + Model.PickerId, Model.User.userName)
#Html.Hidden("UserEmailHidden_" + Model.PickerId, Model.User.userEmail)
<span id="UserEditButton_#Model.PickerId" class="fa fa-pencil icon-inline"></span>
<span id="UserCancelButton_#Model.PickerId" class="fas fa-ban hide icon-inline"></span>
<span id="UserSearchButton_#Model.PickerId" class="fa fa-search hide icon-inline"></span>
#*<span id="InjectButtonPlaceholder_#Model.PickerId" class="hide"></span>*#
<img id="PeoplePickerLoading_#Model.PickerId" class="hide" alt="Loading..." src="~/Images/loading.gif" /><br />
<span id="PeoplePickerError_#Model.PickerId" class="error-label">*</span>
<div id="UserSearchContent_#Model.PickerId" class="list-group user-results"
onmouseout="$('.disable-scroll-container').removeClass('disable-scroll');"
onmouseover="$('.disable-scroll-container').addClass('disable-scroll');">
</div>
</div>
How can I update the fields that start with the word "User" when the view fails validation

I'm going to close this question. I discovered that the issue lies in a different direction and I'm going to post a new question.

Related

how to list dropdown from VIewBag with one to many relation on a partial page?

this is my model.
This is a partial page:
#model FinalForm.Models.Employee
<div class="container">
#using (Html.BeginForm("SaveMarks", "Reg", FormMethod.Post))
{
<div class="form-group">
<button type="button" id="Submit" class="btn btn-info col-md-2" onclick="SubmitM()">Add Marks</button>
<div>
<label class="form-label col-md-1">Qualification</label>
#Html.DropDownList("Quallist", null, "Select", htmlAttributes: new { #class = "form-control search-select offerItem Item border border-dark", id = "Item", #Name = "QualificationList.Q_Name" })
#Html.ValidationMessageFor(model => model.EMP_QUALIFICATION, "", new { #class = "text-danger" })
</div>
<div>
<label class="form-label col-md-1">Marks</label>
<input type="text" id="Marks" name="Marks" class="form-control col-md-1" placeholder="" />
</div>
</div>
}
<div class="panel-body">
<table id="tbl_qlist" class="table table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Q_id</th>
<th>Q_Name</th>
<th>Marks</th>
<th>Del</th>
</tr>
</thead>
</table>
</div>
</div>
this is contoller method:
[ChildActionOnly]
public ActionResult Equalify()
{
ViewBag.Quallist = new SelectList(new List<QualificationList>(), "Q_id", "Q_Name");
return PartialView("Equalify");
}
```
System.InvalidOperationException: 'There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'Quallist'.'

How can I fetch detail of each perticular ID?

In My list view I have all the details of leave. But when I click on details It will display me a Pop-up. In Pop up box it has to fetch and give me all the details of particular field but instead of that it always give me details of last inserted record
Here Is code of my list file
<table id="myTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>Employee Name</th>
<th>Leave Type</th>
<th>Leave Duration</th>
<th>Applied On</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#if($allLeaves != null)
#foreach($allLeaves as $leave)
<tr>
<td> {{ $leave->username }} </td>
<td> {{ $leave->typeOfLeave }} </td>
<td>
{{ $leave->startDate }} To
{{ $leave->endDate }}
</td>
<td> {{ $leave->startDate }} </td>
<td>
#if($leave['status']=='Pending')
<span class="btn btn-warning">Pending</span>
#elseif($leave['status']=='Approved')
<span class="btn btn-success">Approved</span>
#else
<span class="btn btn-danger">Rejected</span>
#endif
</td>
<td>Details</td>
</tr>
</tbody>
</table>
and in same page i wrote code of fetch records
<form id="myform" class="form-horizontal" method="POST" action="{{ route('approve_leave', $leave->id) }}">
#csrf
<div class="card-body">
<div class="row">
<label class="col-md-6"><strong> Employee Name</strong></label>
<div class="col-md-6">
<input type="text" class="form-control" id="emp_name" disabled value="{{$leave->username}}" style="border:none">
</div>
</div>
<br>
<div class="row">
<label class="col-md-6"><strong>Leave Type</strong></label>
<div class="col-md-6">
<input type="text" class="form-control" id="leavetype" disabled value="{{$leave->typeOfLeave}}" style="border:none">
</div>
</div>
<br>
<div class="row">
<label class="col-md-6"><strong>Leave Duration</strong></label>
<div class="col-md-6">
<input type="text" class="form-control" id="leaveduration" disabled value="{{ $leave->startDate }} To {{ $leave->endDate }}" style="border:none">
</div>
</div>
<br>
<div class="row">
<label class="col-md-6"><strong>Reason</strong></label>
<div class="col-md-6">
<input type="text" class="form-control" id="reason" disabled value="{{$leave->reasonForLeave}}" style="border:none">
</div>
</div>
<br>
<div class="row">
<label class="col-md-6"><strong>Applied on</strong></label>
<div class="col-md-6">
<input type="text" class="form-control" id="appliedon" disabled value="{{$leave->startDate}}" style="border:none">
</div>
</div>
<br>
<div class="row">
<label class="col-md-6"><strong>Action</strong></label>
<div class="col-md-6">
<select class="form-control" id="status" name="status" value="{{$leave->status}}">
<option value="Pending" selected="selected">Pending</option>
<option value="Approved">Approved</option>
<option value="Rejected">Rejected</option>
</select>
</div>
</div>
#endforeach
<br>
<div class="row">
<label class="col-md-6"><strong>Reason For Action</strong></label>
<div class="col-md-6">
<input type="text" class="form-control" id="reason" name="reasonForAction" placeholder="Reason Of Action" style="border:none">
</div>
</div>
<br>
<div class="modal-footer">
<button type="submit" class="btn btn-info waves-effect" data-dismiss="modal">Save</button>
<button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Cancel</button>
</div>
</div>
</form>
And This is the code i wrote in controller file
//Code Of list view
public function listOfLeave()
{
$allLeaves = LeaveManagement::all();
return view('pages.leavelist', compact('allLeaves'));
}
//Code of click on details button and fetch record of that particular id
public function handleLeave($id)
{
$leave = LeaveManagement::find($id);
return view('pages.leavelist', compact('leave', 'id'));
}
//code of approve reject leave and change the status of leave
public function approveLeave(Request $request ,$id)
{
$leave = LeaveManagement::find($id);
$leave->status = $request->get('status');
$leave->reasonForAction = $request->get('reasonForAction');
$leave->save();
return view('pages.leavelist');
}
If you want to show data according to user's id then you have to pass each field like data-fieldname and then you can fetch that field's data as shown in script.
Button:
<button type="button"
class="btn btn-xs btn-default confirm-modal"
data-toggle="modal"
data-target="#model"
data-id="{{ $singleRecord->id }}"
data-name="{{ $singleRecord->full_name }}"
data-leave_reason="{{ $singleRecord->leave_reason }}"
data-from_date="{{ date('d-F-Y', strtotime($singleRecord->from_date)) }}"
data-to_date="{{ date('d-F-Y', strtotime($singleRecord->to_date)) }}"
>Details </button>
And add script
<script type="text/javascript">
$('.confirm-modal').click(function (event) {
$('.employee_name').text($(this).data('name'));
$('#from_date').text($(this).data('from_date'));
$('#to_date').text($(this).data('to_date'));
$('#total_leaves').text($(this).data('total_leaves'));
$('.leave_reason').text($(this).data('leave_reason'));
})
</script>
In model div, add each id to display that data.
<div class="col-md-12">
<label for="to_date">To Date:</label>
<span id="to_date"></span>
Hope this helps :)
Edit your modal button and modal id like below,
<td>Details</td>
and your modal,
<div id="details_{{ $leave->id }}" class="modal fade edit-form" role="dialog">
or you can use javascript to populate your field,
<button type="button" class="btn btn-xs btn-default confirm-modal" data-toggle="modal" data-target="#details"
data-leave="{{ $leave }}">Details </button>
<script type="text/javascript">
$(document).on('click', '.confirm-modal', function(e){
var data = $(this).data('leave');
$('#emp_name').text(data.username);
$('#from_date').text(data.from_date');
$('#to_date').text(data.to_date);
$('#total_leaves').text(data.total_leaves);
$('#leave_reason').text(data.leave_reason);
})
</script>

Vue.js - Buefy Modules (Radio btns/ Check Box)

I'm practising back-end in Laravel, and for front-end I'm using Vue.js - Buefy Modules, and I have little problem with Radio and CheckBox.
Here User should choose one of the two offered radio btns:
<div class="block">
<b-radio-group v-model="permissionType">
<b-radio name="permission_type" value="basic">Basic Permission</b-radio>
<b-radio name="permission_type" value="crud">CRUD Permission</b-radio>
</b-radio-group>
</div>
If User click on first btun (Basic) there should appear 3 input fields:
<div class="field" v-if="permissionType == 'basic'">
<label for="display_name" class="label">Name (Display Name)</label>
<p class="control">
<input type="text" class="input" name="display_name" id="display_name">
</p>
</div>
<div class="field" v-if="permissionType == 'basic'">
<label for="name" class="label">Slug</label>
<p class="control">
<input type="text" class="input" name="name" id="name">
</p>
</div>
<div class="field" v-if="permissionType == 'basic'">
<label for="description" class="label">Description</label>
<p class="control">
<input type="text" class="input" name="description" id="description" placeholder="Describe what this permission does">
</p>
</div>
If User click on second btn (CRUD) there should appear 1 input, 4 check box btns and table, but they do not appear.
<div class="field" v-if="permissionType == 'crud'">
<label for="resource" class="label">Resource</label>
<p class="control">
<input type="text" class="input" name="resource" id="resource" v-model="resource" placeholder="The name of the resource">
</p>
</div>
<div class="columns" v-if="permissionType == 'crud'">
<div class="column is-one-quarter">
<b-checkbox-group v-model="crudSelected">
<div class="field">
<b-checkbox custom-value="create">Create</b-checkbox>
</div>
<div class="field">
<b-checkbox custom-value="read">Read</b-checkbox>
</div>
<div class="field">
<b-checkbox custom-value="update">Update</b-checkbox>
</div>
<div class="field">
<b-checkbox custom-value="delete">Delete</b-checkbox>
</div>
</b-checkbox-group>
</div> <!-- end of .column -->
<input type="hidden" name="crud_selected" :value="crudSelected">
<div class="column">
<table class="table" v-if="resource.length >= 3">
<thead>
<th>Name</th>
<th>Slug</th>
<th>Description</th>
</thead>
<tbody>
<tr v-for="item in crudSelected">
<td v-text="crudName(item)"></td>
<td v-text="crudSlug(item)"></td>
<td v-text="crudDescription(item)"></td>
</tr>
</tbody>
</table>
</div>
</div>
I've checked Buefy documentation and there were some updates, but when I change code, still not works..
Here is script:
<script>
var app = new Vue({
el: '#app',
data: {
permissionType: 'basic',
resource: '',
crudSelected: ['create', 'read', 'update', 'delete']
},
methods: {
crudName: function(item) {
return item.substr(0,1).toUpperCase() + item.substr(1) + " " + app.resource.substr(0,1).toUpperCase() + app.resource.substr(1);
},
crudSlug: function(item) {
return item.toLowerCase() + "-" + app.resource.toLowerCase();
},
crudDescription: function(item) {
return "Allow a User to " + item.toUpperCase() + " a " + app.resource.substr(0,1).toUpperCase() + app.resource.substr(1);
}
}
});
</script>
Here I place original code without changes, if someone could fix this, I would be grateful. Thanks!
you forget to add v-model to your radio group, try this and it should work
<div class="block">
<b-radio-group v-model="permissionType">
<b-radio v-model="permissionType" name="permission_type" native-value="basic">Basic Permission</b-radio>
<b-radio v-model="permissionType" name="permission_type" native-value="crud">CRUD Permission</b-radio>
</b-radio-group>

Theme animations don't play

I'm using ABP 2.1.2 and on a form I have some controls hidden in a <div> with an *ngIf but when the <div> is revealed the floating labels don't animate so the user's text is badly merged with the label text.
component.html
<div bsModal #createServiceProviderModal="bs-modal" class="modal fade" (onShown)="onShown()" tabindex="-1" role="dialog"
aria-labelledby="createDigitalAssetModal" aria-hidden="true" [config]="{backdrop: 'static'}">
<div class="modal-dialog">
<div #modalContent class="modal-content">
<div class="modal-header">
<button type="button" class="close" (click)="close()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">
<span>{{l("CreateNewServiceProvider")}}</span>
</h4>
</div>
<div id="identify" *ngIf="step == 'identify'">
<div class="modal-body">
<div class="row clearfix">
<div class="col-sm-12">
<div class="form-group form-float">
<div class="form-line">
<input materialInput id="emailAddress" type="email" name="EmailAddress" [(ngModel)]="serviceProvider.emailAddress" required class="validate form-control">
<label for="emailAddress" class="form-label">{{l("EmailAddress")}}</label>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button [disabled]="saving" type="button" class="btn btn-default waves-effect" (click)="close()">
{{l("Cancel")}}
</button>
<button class="btn btn-info waves-effect" (click)="findServiceProvider()">
{{l("Next")}}
</button>
</div>
</div>
<form *ngIf="active" #createServiceProviderForm="ngForm" id="frm_create_serviceProvider" novalidate (ngSubmit)="save()">
<div id="add" *ngIf="step == 'create'">
<div class="modal-body">
<div class="row clearfix">
<div class="col-sm-12">
<div class="form-group form-float">
<div class="form-line">
<input id="companyName" type="text" name="CompanyName" [(ngModel)]="serviceProvider.companyName" required class="validate form-control">
<label for="companyName" class="form-label">{{l("CompanyName")}}</label>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6">
<div class="form-group form-float">
<div class="form-line">
<input id="name" type="text" name="Name" [(ngModel)]="serviceProvider.name" required class="validate form-control">
<label for="name" class="form-label">{{l("Name")}}</label>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group form-float">
<div class="form-line">
<input id="surname" type="text" name="Surname" [(ngModel)]="serviceProvider.surname" required class="validate form-control">
<label for="surname" class="form-label">{{l("Surname")}}</label>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="form-group form-float">
<div class="form-line">
<input id="emailAddress" type="text" name="emailAddress" [(ngModel)]="serviceProvider.emailAddress" disabled class="validate form-control">
<label for="emailAddress" class="form-label">{{l("EmailAddress")}}</label>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button [disabled]="saving" type="button" class="btn btn-default waves-effect" (click)="close()">
{{l("Cancel")}}
</button>
<button [disabled]="!createServiceProviderForm.form.valid || saving" type="submit" class="btn btn-primary waves-effect">
{{l("Save")}}
</button>
</div>
</div>
<div id="identify" *ngIf="step == 'confirm'">
<div class="modal-body">
<span class="text-success">{{l('ServiceProviderAlreadyExists')}}</span>
<br>
<table class="table">
<tr>
<td class="col-span-3"><label class="pull-right">{{l('Name')}}</label></td>
<td>{{serviceProvider.name}}</td>
</tr>
<tr>
<td><label class="pull-right">{{l('Surname')}}</label></td>
<td>{{serviceProvider.surname}}</td>
</tr>
<tr>
<td><label class="pull-right">{{l('Company')}}</label></td>
<td>{{serviceProvider.companyName}}</td>
</tr>
<tr>
<td><label class="pull-right">{{l('Email Address')}}</label></td>
<td>{{serviceProvider.emailAddress}}</td>
</tr>
</table>
</div>
<div class="modal-footer">
<button [disabled]="saving" type="button" class="btn btn-default waves-effect" (click)="close()">
{{l("Cancel")}}
</button>
<button [disabled]="!createServiceProviderForm.form.valid || saving" type="submit" class="btn btn-primary waves-effect">
{{l("Save")}}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
component.ts
import { Component, ViewChild, Injector, Output, EventEmitter, ElementRef } from '#angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { ServiceProviderServiceProxy, ServiceProviderDto } from '#shared/service-proxies/service-proxies';
import { AppComponentBase } from '#shared/app-component-base';
#Component({
selector: 'create-service-provider-modal',
templateUrl: './create-service-provider.component.html'
})
export class CreateServiceProviderComponent extends AppComponentBase {
#ViewChild('createServiceProviderModal') modal: ModalDirective;
#ViewChild('modalContent') modalContent: ElementRef;
#Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
serviceProvider: ServiceProviderDto = new ServiceProviderDto({id: 0, isUser: false});
step: string = "identify";
active: boolean = false;
saving: boolean = false;
constructor(
injector: Injector,
private serviceProviderService: ServiceProviderServiceProxy,
) {
super(injector);
}
show(): void {
this.active = true;
this.modal.show();
this.serviceProvider = new ServiceProviderDto({id: 0, isUser: false});
this.step = "identify";
}
onShown(): void {
$.AdminBSB.input.activate($(this.modalContent.nativeElement));
}
save(): void {
this.saving = true;
this.serviceProviderService.create(this.serviceProvider)
.finally(() => { this.saving = false; })
.subscribe(() => {
this.notify.info(this.l('SavedSuccessfully'));
this.close();
this.modalSave.emit(null);
});
}
close(): void {
this.active = false;
this.modal.hide();
}
findServiceProvider(): void {
this.saving = true;
abp.ui.setBusy();
this.serviceProviderService.getUserAsProvider(this.serviceProvider.emailAddress)
.finally(() => {
this.saving = false;
abp.ui.clearBusy();
})
.subscribe((next) => {
console.log(next);
if (next.id !== undefined) {
this.serviceProvider = next;
this.step = "confirm";
}
else {
this.step = "create";
}
})
}
}
Issue
When this modal is displayed the variable step is set to "identify" and the first section is displayed where the user must capture the service provider's email address. When the user clicks 'Next' I check if the service provider already exists and then change step to either "create" or "confirm". When the div for creating a service provider is displayed the labels for the input don't animate
Presumably I must re-run some kind of animation script but I cannot figure out what. Please help!
I think the problem was that I needed to call onShown() after revealing the div

Ajax.BeginForm submitting the form twice

I have a problem with my modal on inserting data. Every time I add a new row it get's a second identical row into the database. I don't really know exactly what I did wrong so if you have a ideea on how to solve this please help me.
This is my controller:
public ActionResult IndexEvent()
{
return View(db.tbl_Event.ToList());
}
[HttpGet]
public ActionResult AddEvent()
{
return PartialView();
}
[HttpPost]
public ActionResult AddEvent(BOL3.tbl_Event eve)
{
if(ModelState.IsValid)
{
db.tbl_Event.Add(eve);
db.SaveChanges();
}
return PartialView("_Detail", db.tbl_Event.ToList());
}
,here is my Index view, _Detail partial view and Add partial view (in the same order):
#model IEnumerable<BOL3.tbl_Event>
#{
ViewBag.Title = "Index";
}
<link href="#Url.Content("~/Content/bootstrap/css/bootstrap.min.css")" rel="stylesheet" />
<link href="#Url.Content("~/Content/bootstrap/css/bootstrap-theme.min.cs")" rel="stylesheet" />
<link href="#Url.Content("~/Content/bootstrap/css/font-awesome.min.cs")" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<div id="main-div">
<div class="clearfix"> </div>
<div class="clearfix"> </div>
<div class="container">
<i class="glyphicon glyphicon-plus"></i> Add New
<br />
<br />
<div id="div-record">
#Html.Partial("_Detail")
</div>
</div>
</div>
<div class="modal fade" id="Add-Model" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add Event</h4>
</div>
<div class="divForAdd">
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$('#Add').click(function (event) {
event.preventDefault();
$.get(this.href, function (response) {
$('.divForAdd').html(response);
});
$('#Add-Model').modal({
backdrop: 'static',
}, 'show');
});
#model IEnumerable<BOL3.tbl_Event>
<div class="table-responsive">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Event Name</th>
<th>Starting Event (Date and Time)</th>
<th>Ending Event (Date and time)</th>
<th>All Day ?</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
#foreach(var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Event)
</td>
<td>
#Html.DisplayFor(modelItem => item.Start_Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.End_Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.All_Day)
</td>
<td>
<i class="glyphicon glyphicon-pencil"></i> Edit
</td>
<td>
#Ajax.ActionLink(" Delete", "DeleteEvent", "Prog", new { #id = item.ID }, new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "div-record" }, new { #class = "glyphicon glyphicon-trash" })
</td>
</tr>
}
</tbody>
</table>
</div>
#model BOL3.tbl_Event
#using (Ajax.BeginForm("AddEvent", "Prog", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "div-record", OnSuccess = "$('.close').click()" }))
{
<div class="modal-body">
<div class="row form-group">
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pushpin"></i></span>
#Html.TextBoxFor(m => m.Event, new { #class = "form-control" })
</div>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
#Html.TextBoxFor(m => m.Start_Date, new { #class = "form-control" })
</div>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
#Html.TextBoxFor(m => m.End_Date, new { #class = "form-control" })
</div>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
#Html.TextBoxFor(m => m.All_Day, new { #class = "form-control" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success" name="cmd">Save</button>
</div>
}
I tried something else but that also gave me a problem (see this link: "Refresh table list using Ajax in Asp.Net Mvc") Thank you.
this problem is occuring because you have loaded <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script> twice in the _layout page as well as index page and because of that it causes ajax to send request twice. so remove the link either from Index page or _layout page
Why it causes to submit twice?
if you look at the code of unobtrusive-ajax it has function $(document).on("click", "form[data-ajax=true] which is responsible for sending the request so when you submit the form this function trigger's differently on each script you loaded which causes the request to send twice (if someone can explain better feel free to edit)
It is because you have JS function binded to element #Add and you are not disabling anchror href correctly, thus having two requests (since your anchor has link attribute as well). In this SO question How can I disable HREF if onclick is executed? you can se, that correct click handling should be like
$('#Add').click(function (event) {
event.preventDefault();
$.get(this.href, function (response) {
$('.divForAdd').html(response);
});
$('#Add-Model').modal({
backdrop: 'static',
}, 'show');
return false; // this is essential
});

Resources