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

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);
});

Related

Spring MVC Controller not receiving atribute from Template with Thymeleaf

I have a template which represents a list of notes that are retrieved from a database
<tr th:unless="${#lists.isEmpty(allNotes)}"
th:each="note : ${allNotes}">
<td>
<form action="#" method="POST" th:action="#{/home/editNote}"
th:object="${note}">
<input type="hidden" id="noteId" name="noteId" th:value="*{noteId}">
<button type="button" class="btn btn-success"
onclick="editNoteModal('updateNote', this.getAttribute('data-noteId'),
this.getAttribute('data-noteTitle'),
this.getAttribute('data-noteDescription'))">Edit
</button>
</form>
<form action="#" method="POST" th:action="#{/home/deleteNote}">
<input type="hidden" name="noteId" th:value="*{note.noteId}">
<a class="btn btn-danger">Delete</a>
</form>
</td>
<th scope="row" th:text="${note.noteTitle}">Example Note Title</th>
<td th:text="${note.noteDescription}">Example Note Description</td>
</form>
</tr>
</tbody>
In the GUI It looks like this
This is my modal code which should open after I click on the edit button:
<div class="modal fade" id="editNoteModal" tabindex="-1" role="dialog" aria-labelledby="noteModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="editnoteModalLabel">Note</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group">
<label for="note-title" class="col-form-label">Title</label>
<input type="text" name="noteTitle" class="form-control" id="editNoteTitle"
maxlength="20" required>
</div>
<div class="form-group">
<label for="note-description" class="col-form-label">Description</label>
<textarea class="form-control" name="noteDescription" id="editNoteDescription"
rows="5" maxlength="1000" required></textarea>
</div>
<button id="editNoteSubmit" type="submit" class="d-none"></button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="$('#editNoteModal').click();">
Save
changes
</button>
</div>
</div>
</div>
</div>
</div>
In the GUI it looks like this:
I want to be able to edit given note and then send the edited id to the controller so I can update this change within the database. I have correct database logic for the update, I just don't know the way how to send the given notes id and changed information to my controller.
#PostMapping("/editNote")
public String editNote(#ModelAttribute(value = "note") Note note,
#ModelAttribute(value = "noteId") NoteIdModel noteIdModel, Model model,
Authentication authentication) {
System.out.println("noteid " + note.getNoteId());
System.out.println("noteidHidden " + noteIdModel.getNoteIdHidden());
System.out.println("notedesc" + note.getNoteDescription());
noteService.editNote(note, authentication);
return "result";
}
However, the incoming noteId is null. I have checked the database and the note with correct id is indeed in the database and is also retrieved from the database. It's just not sent to the controller.
Try this one:
HTML fragment
<tr th:unless="${#lists.isEmpty(allNotes)}"
th:each="note : ${allNotes}">
<td>
<button type="button" class="btn btn-success"
th:data-noteId="${note.noteId}"
th:data-noteTitle="${note.noteTitle}"
th:data-noteDescription="${note.noteDescription}"
onclick="editNoteModal('updateNote', this.getAttribute('data-noteId'),this.getAttribute('data-noteTitle'),this.getAttribute('data-noteDescription'))">Edit
</button><br/>
<a class="btn btn-danger">Delete</a>
</td>
<td scope="row" th:text="${note.noteTitle}"></td>
<td th:text="${note.noteDescription}"></td>
</tr>
JS fragment
/**
* Fill edit modal with current information
*/
function editNoteModal(modal, noteId, noteTitle, noteDescription) {
$('#editnoteModalLabel').text("Note " + noteId);
$('#editNoteId').val(noteId);
$('#editNoteTitle').val(noteTitle);
$('#editNoteDescription').val(noteDescription);
$('#editNoteModal').modal("show");
}
/**
* Save to backend edit information
*/
function save() {
var noteId = $('#editNoteId').val();
var noteTitle = $('#editNoteTitle').val();
var noteDescription = $('#editNoteDescription').val();
$.ajax({
url : "./editNote",
method : "POST",
headers : {
'Content-Type' : 'application/json'
},
data : JSON.stringify({
noteId : noteId,
noteTitle : noteTitle,
noteDescription : noteDescription
}),
success : function(result) {
$('#editNoteModal').modal("hide");
alert(result);
}
})
}
Backend
#PostMapping(path = "/editNote", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> editNote(#RequestBody Note note) {
System.out.println("noteid " + note.getNoteId());
System.out.println("noteidTitle " + note.getNoteTitle());
System.out.println("notedesc" + note.getNoteDescription());
//Save in database
return ResponseEntity.ok("OK");
}
This is how I did while I was trying to pass the id to open a modal by finding details using that id:
<a href="#" class="btn btn-sm btn-primary"
th:data-parameter1="${user.useruuid}"
onclick="openUserModal(this.getAttribute('data-parameter1'));">Details</a>
And then somewhere in your JavaScript, you can something (similar) like this:
<script type="text/javascript" th:fragment="includeModalScript">
function openUserModal(id) {
$.ajax({
url: "/findOnebyId?id="+ id,
success: function(data){
alert(id);
.......
</script>
And my controller looked like this:
#GetMapping("/findOnebyId")
#ResponseBody
public AppUser findOneByUUID(String id) {
....
}
You can take a look here, here and here for a working demo similar to your issue/requirement.

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

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

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.

How do I load an object in a Bootstrap modal using Spring Boot / Thymeleaf?

I have a table filled with tasks:
<table class="table" id="tasksTable">
<thead class="thead-inverse">
<tr>
<th>ID</th>
<th>Title</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr data-th-each="task : ${tasks}">
<td data-th-text="${task.id}">Task ID</td>
<td data-th-text="${task.title}">Task Title</td>
<td><a th:href="#{/tasks/delete/{id}(id=${task.id})}"
class="btn btn-danger">Delete</a> -
<button class="btn btn-warning" data-toggle="modal"
data-th-id="${task.id}" data-target="#updateTaskModal">Update</button></td>
</tr>
</tbody>
</table>
The list is sent from a controller like this:
#GetMapping(path = "/")
public String getAllUsersView(Model model) {
List<User> users = new ArrayList<>();
List<Task> tasks = new ArrayList<>();
User user = new User();
Task task = new Task();
userRepository.findAll().forEach(users::add);
taskRepository.findAll().forEach(tasks::add);
model.addAttribute("users", users);
model.addAttribute("tasks", tasks);
model.addAttribute("user", user);
model.addAttribute("task", task);
return "view";
}
I would like to pick one task from the table, and send it to a modal. For instance, let's say I have 10 tasks. I want to pick task #5 and be able to update it. When I click Update, I can open a modal, but I don't know how to fill the form with the data from that specific task, it all comes blank.
This is my modal:
<div id="updateTaskModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Update Task</h4>
</div>
<div class="modal-body">
<form id="updateNewTask" action="#" th:action="#{/tasks/update}"
th:object="${task}" method="put">
<input type="text" class="form-control" name="title" id="title"
th:field="*{title}" placeholder="Task Title" />
<hr />
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success pull-right">Update</button>
</form>
</div>
</div>
</div>
</div>
What would be the best practice to achieve this? Is it possible to send the entire object thru a button? If not, how can I load my object into the modal? I can retrieve a JSON version of the object via /tasks/{taskId}, but I don't know how to call it from the modal.
You can load content into existing modal with Javascript. "Best" way to to this is by rendering your object on server into some HTML with thymleaf and then fetching this response via Ajax and injecting into your modal box into some div tag.

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