Asp.net MVC - error after second attempt on opening a modal window - ajax

I am trying to implement bootstrap modal window when opening details. The modal window is open on ajax call. The problem is, I can only open it once. It opens with whole template, while it should not and during the second attempt I get error:
Uncaught error: modal is not a function
Then I get this error and can not open modal window any more.
Container for main view:
<div id="data-container">
#Html.Action("PartialDisplay", "Disp")
</div>
I display all data in partial view, so the controller looks like this:
public ActionResult Display()
{
return View();
}
public PartialViewResult PartialDisplay(int[] checkId)
{
if (checkId == null)
{
[my code]
return PartialView(viewModel);
}
details view:
#{
ViewBag.Title = "PartialDisplay";
Layout = null;
}
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Detail</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="modalContent">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<table class="table">
<thead>
<tr>
<th>Nazev Jidla</th>
<th>Kategorie</th>
<th>Akce</th>
</tr>
</thead>
<tbody>
#foreach (Jidlo jidlo in Model.Jidlos)
{
<tr>
<td>
#Html.DisplayFor(modelItem => jidlo.name)
</td>
<td>
#Html.DisplayFor(modelItem => jidlo.Category.popis)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = jidlo.JidloID }) |
#Ajax.ActionLink("Details","Details", new { id = jidlo.JidloID }, new AjaxOptions(){ UpdateTargetId = "modalContent", InsertionMode = InsertionMode.Replace, OnBegin = "openModalWindow" }) |
#Html.ActionLink("Delete", "Delete", new { id = jidlo.JidloID }, new { onclick = "return confirm('opravdu smazat polozku " + jidlo.name + "?');" })
</td>
</tr>
}
</tbody>
</table>
<script type="text/javascript">
function openModalWindow() {
$('#myModal').modal("show");
}
</script>
Controller Action:
public ActionResult Details(int id = 0)
{
Jidlo jidlo = db.Jidlos.Find(id);
if (Request.IsAjaxRequest())
{
return PartialView(jidlo);
}
else {
return View(jidlo);
}
}
Layout scripts included:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="#Url.Content("~/Scripts/jquery-3.2.1.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
<script src="#Url.Content("~/Scripts/bootstrap.js")"></script>
What am I missing here? I tried to change priority for loading and couple more things like add jQuery.noConflict to script and still nothing.

Problem is loading jquery script twice
<script src="#Url.Content("~/Scripts/jquery-3.2.1.js")"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")"></script>
<script src="#Url.Content("~/Scripts/bootstrap.js")"></script>
That is correct.
Another this was removing the template markup in the details view.

Related

Why Does Image Read Null When I Try To Delete My Category?

I am trying to find a way to delete my category that I have created. I have the image stored in my public folder and I get the error attempt to read image is null, I think the error has to do with category_id being null. How can I retrieve it for my category object?
//Controller class
class Index extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public $category_id;
//setting category_id
public function deleteCategory($category_id)
{
$this->category_id = $category_id;
}
public function destroyCategory() {
$category = Category::find($this->category_id);
// dd($this);
$path = 'uploads/category/'.$category->image;
if (File::exists($path)) {
File::delete($path);
}
$category->delete();
session()->flash('message', 'Category Deleted');
$this->dispatchBrowserEvent('close-modal');
}
public function render()
{
$categories = Category::orderBy('id', 'DESC')->paginate(10);
return view('livewire.admin.category.index', ['categories' => $categories]);
}
}
this is my component blades file that accompanies it.
//my blade file
<div>
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Category Delete</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form wire:submit.prevent="destroyCategory">
<div class="modal-body">
<h6>Are you sure you want to delete this data?</h6>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Yes. Delete</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
#if(session('message'))
<div class="alert alert-success">{{session('message')}}</div>
#endif
<div class="card-header">
<h4>
Category
Add Category
</h4>
</div>
<div class="card-body">
{{-- display all categories using livewire --}}
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($categories as $category)
<tr>
<td>{{$category->id}}</td>
<td>{{$category->name}}</td>
<td>{{$category->status == '1' ? "Hidden" : "Visible"}}</td>
<td>
Edit
<a href="#" wire:click="deleteCategory({{$category->id}})" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
Delete
</a>
</tr>
#endforeach
</tbody>
</table>
<div>
{{$categories->links()}}
</div>
</div>
</div>
</div>
</div>
#push('script')
<script>
window.addEventListener('close-modal', event => {
$('#deleteModal').modal('hide');
})
</script>
#endpush
I wanted to add my sugestion as a comment, however is to long and it doesn't look good when i add the code, so i need to add a post.
I see that you are using deleteCategory() to get category_id and set it on a public varaible public $category_id;, when you get the variable then you try to delete the category with destroyCategory().
If that is true you don't need to create 2 functions for that,
so instead try and use this:
public function deleteCategory($category_id) {
$category = Category::find($category_id);
$path = 'uploads/category/'.$category->image;
// dd($path); <- try this on the debbuger, to see the path
if (File::exists($path)) {
File::delete($path);
}
$category->delete();
session()->flash('message', 'Category Deleted');
$this->dispatchBrowserEvent('close-modal');
}
Just use the function deleteCategory with the code of destroyCategory, and let the paramenter $category_id, because deleteCategory gets the id from the view
wire:click="deleteCategory({{$category->id}})"

How to pass a value from foreach loop in the view to the controller in ASP.NET Core MVC?

I have a table in my view that its rows are filled by a foreach loop. A part of this table is as follows:
#foreach (var item in Model.PmModel)
{
<td>#Html.DisplayName(item.pmNumber.ToString())</td>
<td>
<button type="button" class="btn btn-info btn-table btn-modal">Upload</button>
</td>
}
I have a button in each rows and by pressing each of them, a modal form is appeared to upload a file. I use the following code to upload the file and fill database columns based on the file information. But I need to take pmId from view to the following action:
public async Task<IActionResult> UploadFile(IFormFile file)
{
if (file != null)
{
if (file.Length > 0)
{
var fileName = Path.GetFileName(file.FileName);
var fileExtension = Path.GetExtension(fileName);
var newFileName = string.Concat(Convert.ToString(Guid.NewGuid()), fileExtension);
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/PmFiles/UploadedByUsers", newFileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
var fileElements = new Models.FileRepository()
{
fileId = 0,
fileName = newFileName,
isDownloaded = false,
pm = _pmRepository.GetPmById(int Id), //I need to get Id from view
uploadDate = DateTime.Now,
};
_fileRepository.InsertFile(fileElements);
_fileRepository.SaveChanges();
}
}
return RedirectToAction("PmPage");
}
I use Bootstrap modal:
#section Modal{
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"
dir="ltr">
<div class="modal-dialog">
<form method="post" enctype="multipart/form-data" asp-controller="Page" asp-action="UploadFile">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">File Upload</h5>
<button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row mt-2" dir="rtl">
<label class="form-label" for="customFile">Select your file:</label>
<input type="file" name="file" class="form-control" id="customFile" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-mdb-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-danger">Upload</button>
</div>
</div>
</form>
</div>
</div>
}
In view, I can find pmId using item.pmNumber but I don't know how I can take its value to my controller. Please help me.
Update: This script triggers the modal by pressing the button.
<script type="text/javascript">
$(document).ready(function () {
$('.btn-modal').click(function () {
$('#exampleModal').modal('show');
});
});
</script>
You can add a hidden input in your modal and put the modal body in the foreach section to pass the item.pmNumber to hidden input.
Here is a working demo you could follow:
Model:
public class FileModel
{
public List<PmModel> PmModel { get; set; }
}
public class PmModel
{
public int pmNumber { get; set; }
}
View:
#model FileModel
#{
int i = 0; //add this....
}
#foreach (var item in Model.PmModel)
{
<td>#Html.DisplayName(item.pmNumber.ToString())</td>
<td> //change here....
<button type="button" data-toggle="modal" data-target="#exampleModal_#i" class="btn btn-info btn-table btn-modal">Upload</button>
</td> //change here.....
<div class="modal fade" id="exampleModal_#i" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"
dir="ltr">
<div class="modal-dialog">
<form method="post" enctype="multipart/form-data" asp-controller="Page" asp-action="UploadFile">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">File Upload</h5>
<button type="button" class="btn-close" data-mdb-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row mt-2" dir="rtl">
<!--add this-->
<input hidden name="id" value="#item.pmNumber" />
</div>
<div class="row mt-2" dir="rtl">
<label class="form-label" for="customFile">Select your file:</label>
<input type="file" name="file" class="form-control" id="customFile" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-mdb-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-danger">Upload</button>
</div>
</div>
</form>
</div>
</div>
i++; //add here.........
}
#section Scripts {
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
<!-- Google Fonts -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap">
<!-- Bootstrap core CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet">
<!-- Material Design Bootstrap -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/css/mdb.min.css" rel="stylesheet">
<!-- JQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Bootstrap tooltips -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.4/umd/popper.min.js"></script>
<!-- Bootstrap core JavaScript -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.min.js"></script>
<!-- MDB core JavaScript -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/js/mdb.min.js"></script>
}
Controller:
public class PageController : Controller
{
public async Task<IActionResult> UploadFile(IFormFile file,int id)
{
//do your stuff...
return View();
}
}
Besides, you can also create a partial view for modal(This partial view still needs a hidden input) to avoid looping modal body code. Refer to this answer

How to send a list of data from controller to a modal popup in razor

I'm implementing asp.net core 3.1 project. I have a razor view and in razor, I'm showing some data that are getting from the Index method in my controller which its name is RequestorsController. In razor, for each row there is a link which is called "Details" and I want when the user clicks on the Details button for each row, the related id for that row passes to a method called "Details" in RequestorsController and a list of related data returns back to the razor view and displays on a Modal popup. Now I could implement the Modal popup, but my problem is I couldn't fetch the data from the controller to show on modal. I appreciate if anyone solves my problem.
<div id="tablecontainer" class="my-5 col-sm-12 d-flex justify-content-center">
<table id="myDummyTable" class="table m-table mytable table-striped mb-4 col-12 dataTable table-bordered px-0 mx-0" style="box-sizing:content-box;">
<thead>
<tr id="headerrow">
<th>
requestor name
</th>
<th>
items requested
</th>
<th>
operations
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.HiddenFor(modelItem => item.applicantID)
#Html.DisplayFor(modelItem => item.requestorName)
</td>
<td>
#Html.DisplayFor(modelItem => item.requesteditemCount)
</td>
<td>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-id="#item.applicantID">Details</button>
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">New message</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="post">
<div class="modal-body">
<div class="form-group">
<label for="recipient-apiname" class="col-form-label">name:</label>
<input type="text" class="form-control" id="recipient-apiname" name="apiname">
<input type="hidden" id="recipient-id" name="id" />
</div>
<div class="form-group">
<label for="recipient-status" class="col-form-label">status:</label>
<input type="text" class="form-control" id="recipient-status" name="status">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Save" />
</div>
</form>
</div>
</div>
</div>
#section scripts{
<script>
#{
if (ViewBag.ModalState == null)
{
ViewBag.ModalState = "hide";
}
}
$('#exampleModal').modal('#ViewBag.ModalState');
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
var id = button.data('id');
var modal = $(this);
modal.find('.modal-body input[name="id"]').val(id);
$.get('#Url.Action("Details", "Requestors")/' + id, function (data) {
modal.find('.modal-body input[name="name"]').val(data.itemName);
modal.find('.modal-body input[name="status"]').val(data.requestStatus);
});
});
</script>
}
public async Task<IActionResult> Details(int? id)
{
List<ItemDTO> al = new List<ItemDTO>();
ItemDTO apDTO;
var myquery = (from t in _context.Items
where t.ApplicantId == id
select new { ItemName = t.ItemName, requestStatus = t.LastRequestStatus }).ToList();
foreach (var index in myquery)
{
apDTO = new ItemDTO();
apDTO.itemName = index.itemName;
apDTO.requestStatus = index.requestStatus;
al.Add(apDTO);
}
return View(al);
}
Now I could implement the Modal popup, but my problem is I couldn't
fetch the data from the controller to show on modal.
As mentioned in your comment, when you click on the Details button, a 500 error occurs,I did reproduce this mistake.
This is because the Details action returns the View instead of the json data that needs to be returned in ajax, and because there is no Details view, a 500 error occurs.
To solve it, you only need to change the content of the Details action returned to Json data, as shown below:
public async Task<IActionResult> Details(int? id)
{
List<ItemDTO> al = new List<ItemDTO>();
ItemDTO apDTO;
var myquery = (from t in _context.Items
where t.ApplicantId == id
select new { ItemName = t.ItemName, requestStatus = t.LastRequestStatus }).ToList();
foreach (var index in myquery)
{
apDTO = new ItemDTO();
apDTO.itemName = index.ItemName;// here is ItemName(case sensitive)
apDTO.requestStatus = index.requestStatus;
al.Add(apDTO);
}
return Json(al);
}
My doubt is that if the ApplicantId is the key, then the count of data obtained from the Items table must be one, without the need for a list collection, but because you return a collection data, then in ajax, you need to pass data[0] to bind the corresponding input value/
And you need to change input[name="name"] to input[name="apiname"].
Here is ajax code:
$.get('#Url.Action("Details", "Requestors")/' + id, function (data) {
modal.find('.modal-body input[name="apiname"]').val(data[0].itemName);
modal.find('.modal-body input[name="status"]').val(data[0].requestStatus);
});

Change Data in DataTable with Select from Dropdownlist

I have a view with a Datatable, and I want to change the data every time I select a category from a drop-down list.
I want to only display the albums from the selected category, or all albums from all categories, using Ajax and jQuery. The drop-down list must be placed above the table.
Here is my code:
#using System.Collections.Generic;
#using CakeStore.App.Areas.Admin.Models.Albums;
#using CakeStore.App.Services.Contracts;
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#inject IAlbumService AlbumService
#{ ViewData["Title"] = "Category Albums";
Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
var albums = ViewBag.CategoryAlbums as List<AlbumTableViewModel>;
}
<h1 class="text-center text-header-page">Category Albums</h1>
<hr class="hr-admin-divider" />
<div class="form-group">
<a class="btn button-black-white d-flex justify-content-left" href="/Admin/Albums/Create">Create</a>
</div>
<hr class="hr-admin-divider" />
<div class="d-flex">
<table class="table table-striped table-hover" id="myTable">
<tr>
<th>#</th>
<th>Name</th>
<th>Category</th>
<th></th>
<th></th>
<th></th>
</tr>
#for (int i = 0; i < albums.Count(); i++) {
<tr>
<td class="col-md-1">#albums[i].Id</td>
<td class="col-md-3">#albums[i].Name</td>
<td class="col-md-2">#albums[i].Category</td>
<td><a class="btn button-table-edit" href="/Admin/Albums/Edit?id=#albums[i].Id">EDIT</a></td>
<td><a class="btn button-table-delete d-flex justify-content-right" href="/Admin/Albums/Delete?id=#albums[i].Id">DELETE</a></td>
<td><a class="btn button-table-view d-flex justify-content-right" href="/Admin/Products/CategoryAlbums?id=#albums[i].Id">PRODUCTS</a></td>
</tr>
}
</table>
</div>
<div class="row d-flex align-items-end flex-column" style="font-size:12px">
<a class="btn-link pull-right col-lg-2" asp-controller="Categories" asp-action="Category">Back to Categories</a>
</div>
#section Scripts {
<partial name="_ValidationScriptsPartial" />
}
You could use the Partial View ,I made the demo ,you could refer to it
Use ajax to call the GetCityList method to get the data corresponding to the countryId passed .
<div class="form-group">
<label class="col-form-label">Country</label>
<select class="form-control" asp-items="#ViewBag.Country" id="selectlist">
<option>All</option>
</select>
</div>
<div class="form-group" id="cityListWrapper">
<partial name="_CityListPartial" model="#ViewBag.City" />
</div>
#section Scripts
{
<script type="text/javascript">
$("#selectlist").change(function () {
var countryId = $("#selectlist").val();
$.ajax
({
type: "GET",
url: "/Countries/GetCityList?CountryId="+countryId,
success: function (result) {
$("#cityListWrapper").html(result)
}
});
});
</script>
}
Initial rendering the main view , show all albums when not selected
public async Task<IActionResult> Index()
{
ViewBag.Country = new SelectList(_context.Country, "Id", "CountryName");
ViewBag.City = _context.City.ToList();
return View();
}
The GetCityList action ,render the partial view using a statement that returns different values
[HttpGet]
public async Task<IActionResult> GetCityList(int? countryId)
{
if (countryId == null)
{
var CityList = await _context.City.ToListAsync();
return PartialView("_CityListPartial", CityList);
}
var Cities =await _context.City.Where(c => c.Country.Id == countryId).ToListAsync();
return PartialView("_CityListPartial", Cities);
}
How it works

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