I'm using asp.net mvc i want to update data in database using a bootsrap modal
And partial Views.
The broblem is when i click on the link to show the Model it's not working (it shows an empty modal)
this is my Code:
//the Controller Action
public ActionResult Edit(int id = 0)
{
Tache tache = db.Taches.Find(id);
if (tache == null)
{
return HttpNotFound();
}
return PartialView("PartialEdit", tache);
}
// the index View that contain the link and the modal definition :
<td>
<a data-modal='' href='"/Tache/edit/"+#item.TacheId' data-id="#item.TacheId" id="#item.TacheId " title=" edit">Edit </a> |
#Html.ActionLink("Delete", "Delete", new { id = item.TacheId })
</td>
<div id='myModal' class='modal fade'>
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
// and this is the Partial View
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Nouvelle Tâche</h4>
</div>
#using (Html.BeginForm("Create", "Tache", FormMethod.Post, new { #id = "formId" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.TacheId)
<div class="modal-body">
//Some forms in inputs
<div class="row">
// Finaly my javascript :
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$('#progress').show();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
$('#progress').hide();
location.reload();
} else {
$('#progress').hide();
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
});
}
I think the problem may came from the link that somthing is missing their !!
but i'm not sure
if someone can help me that will be great
Think you
As I have said in my comment the code works perfectly now.
In my Index view I have replaced this:
<a data-modal='' href='"/Tache/edit/"+#item.TacheId' data-id="#item.TacheId" id="#item.TacheId " title=" edit">Edit </a>
To this:
<a data-modal='' href="#Url.Action("Edit", "Tache", new { id = item.TacheId })" data-id="#item.TacheId" id="#item.TacheId " title=" edit">Modifier </a>
Related
After the article is successfully added, the modal showing the message should appear, but I'm just getting errors. So far this is my code:
Modal:
<div id="myModal" class="modal fade">
<div class="modal-dialog modal-confirm">
<div class="modal-content">
<div class="modal-header">
<div class="icon-box">
<i class="material-icons"></i>
</div>
<h4 class="modal-title">Awesome!</h4>
</div>
<div class="modal-body">
<p class="text-center">Your booking has been confirmed. Check your email for detials.</p>
</div>
<div class="modal-footer">
<button class="btn btn-success btn-block" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
Ajax:
<script type="text/javascript">
$('#form').on('submit', function (e) {
e.preventDefault();
var f = CKEDITOR.instances.text.getData();
var text = String(f);
var n=text.length;
var title = $('#title').val();
var docu_id = $('#docu_id').val();
var hidden_snippet = $('#hidden_snippet').val();
if (n!=0) {
$.ajax({
type: 'POST',
url: '/knowmore/index.php/ask_controller/book_add',
data: {text:text,title: title,hidden_snippet: hidden_snippet,docu_id:docu_id},
success: function (data)
{
$("#myModal").modal('show')
location.replace('/knowmore/index.php/index_controller/documentation/'+docu_id+'');
}
});
} else { alert('Enter contents of the Article!'); }
});
</script>
I used $("#myModal").modal('show') to show it but all I'm getting is an error saying modal is not a function.
If you all you need is to open a bootstrap modal, then just use
$('#myModal').modal();
It's because jQuery doesn't know any function named modal by default. If you want to show the modal you can just use show() function.
Change following
success: function (data) {
$("#myModal").modal('show')
location.replace('/knowmore/index.php/index_controller/documentation/' + docu_id + '');
}
into
success: function (data) {
$("#myModal").show();
location.replace('/knowmore/index.php/index_controller/documentation/' + docu_id + '');
}
Write down the following code.
success: function(msg)
{
$("#myModel").modal("show");
}
In my Index view.I have a Table with action link. In Action link I am passing some arguments on the base of arguments I execute query if query result is null I want to show the modal present in the Index View.
My Table is.
#foreach(var j in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => j.job_title)</td>
<td>#Html.DisplayFor(modelItem => j.job_description)</td>
<td>#Html.DisplayFor(modelItem => j.apply_before)</td>
<td>#Html.ActionLink( "Apply","applyingjobs","Student",
new {
id= #TempData["data"]
},
null
)
</td>
</tr>
}
My contoller Function which is receiving passed parameter is.
public ActionResult applyingjobs(String id)
{
SqlConnection con = new SqlConnection("xxxxxxxxxxx");
SqlCommand cmd = new SqlCommand();
con.Open();
cmd.CommandText = "select count(*)from Users where id='" + id + "'and " + "type = " + 2 + " and exe!= null and qua!= null" ;
cmd.Connection = con;
Int32 countnamefieldadd = (Int32)cmd.ExecuteScalar();
if (countnamefieldadd == 0)
{
//here I want to show modal which is present in Index Page
}
else
{
return RedirectToAction("Index", "Student", new
{
id = id,
});
}
return RedirectToAction("Index", "Student", new
{
id = id,
});
}
My Modal Code is
<div id="modal_dialog" style="display: none">
// Modal content
</div>
Script to call Modal is
<script type="text/javascript">
$(function () {
$("#modal_dialog").dialog({
title: "Add Record",
open: function (type, data) { $(this).parent().appendTo("form"); },
modal: true
});
return false;
})
</script>
You can use Tempdata in your controller to retain the value and use it as a flag to check whether query returns records or not.
Try this. I hope it helps :)
HTML
#Html.ActionLink("Apply", "applyingjobs", "Employee")
<div>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
Script
$(document).ready(function ()
{
if ('#TempData["value"]' != "" || '#TempData["value"]' != null)
{
if ('#TempData["value"]' == "No Records")
{
$("#myModal").modal('show');
}
else {
$("#myModal").modal('hide');
}
}
});
Controller
public ActionResult applyingjobs()
{
var c = Repository.SelectAll().ToList();
if (c.Count() > 0)
{
return RedirectToAction("Create");
}
else
{
TempData["value"] = "No Records";
return RedirectToAction("Create");
}
}
I am currently dynamically setting data attributes on widgets which are ID's through javascript, I then get the attribute when I go to delete the widget so I can remove the widget entry from the database. I have stepped through the code in firebug and it seems to get the widgetID fine, but when I go to make an ajax post request it does not seem to append the ID for the routing value.
Here is the modal:
div class="modal fade" id="deleteWidgetModal" 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" id="myModalLabel">Delete widget?</h4><!--add depending on which panel you have clicked-->
</div>
<div class="modal-body" id="myModalBody">
<!--Depending on which panel insert content-->
#using (Html.BeginForm("DeleteWidgetConfirmed", "Dashboard", FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
#Html.AntiForgeryToken();
<div class="form-horizontal">
Do you wish to delete this widget?
<div class="form-group">
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" value="DeleteWidgetConfirmed" class="btn btn-danger btn-ok" id="delete-widget">Delete</button>
</div>
</div>
</div>
}
</div>
</div>
</div>
Here is my rendered HTML for the widget where the widgetID is set:
<div class="panel panel-default" draggable="true" data-widgetid="4">
<div class="panel-heading">
<div class="panel-body">
I then try to make a post:
$(document).ready(function () {
$('#columns').on('click', '.glyphicon.glyphicon-trash', function (event) {
var panel = this;
//get id here
//toggle the modal
$('#deleteWidgetModal').modal('show');
var widgetID = $(this).closest('.panel.panel-default').attr('data-widgetid');
document.getElementById('delete-widget').onclick = function (event) {
event.stopPropagation();
//anti forgery token
var form = $('#__AjaxAntiForgeryForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
var URL = '/Dashboard/DeleteWidgetConfirmed';
console.log(widgetID + " test1");
//we make an ajax call to the controller on click
$.ajax({
url: URL,
data: {
__RequestVerificationToken: token,
id: widgetID
},
type: 'POST',
dataType: 'json',
success: function(data){
var parentElement = $(panel).closest(".col-md-4.column");
var targetElement = $(panel).closest(".panel.panel-default");
targetElement.remove();
//parentElement.addClass("expand-panel");
checkEmptyPanelContainers();
$('#deleteWidgetModal').modal('hide');
},
error: function (response) {
console.log(widgetID + " ERROR");
}
})
}
})
});
and here is my HTTP POST request which I got from the NET panel in firebug:
/Dashboard/DeleteWidgetConfirmed
and here is my controller:
// POST: DashboardModels/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteWidgetConfirmed(int? id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DashboardModel dashboardModel = db.dashboards.Find(id);
db.dashboards.Remove(dashboardModel);
db.SaveChanges();
return new EmptyResult();
}
Here is the parameter being passed through with my response:
http://gyazo.com/696b684cc3650dd24731ad8ecdce1447
I am working on an asp.net mvc5 web application, and i am facing a problem as jquery is not loading if i do ajax paging inside my webgrid.
I got the following.The main view which have the grid:-
#model SkillManagement.Models.PagedList<SkillManagement.Models.Phone>
#{
ViewBag.Title = "Phone List";
}
<h1>Phone List</h1>
<div class="well">
#using (Html.BeginForm("index", null, FormMethod.Get))
{
<div style="margin-top:17px;">
#{
var grid = new WebGrid(
canPage: true,
rowsPerPage: Model.PageSize,
canSort: true,
ajaxUpdateContainerId: "grid");
grid.Bind(Model.Content, rowCount: Model.TotalRecords, autoSortAndPage: false);
grid.Pager(WebGridPagerModes.All);
#grid.GetHtml(htmlAttributes: new { id = "grid" }, // id for ajaxUpdateContainerId parameter
fillEmptyRows: false,
tableStyle: "table table-bordered table-hover",
mode: WebGridPagerModes.All,
columns: grid.Columns(
grid.Column("PhoneId", "ID"),
//code goes here
grid.Column(header: "Action", canSort: false, style: "action",
format: #<text>
#Html.Raw("<a data-modal='' href='/phone/details/" + item.PhoneId + "' id='" + item.PhoneId + "' title='Detail'> <span class='glyphicon glyphicon-search'> </span> </a>")
#Html.Raw("<a data-modal='' href='/phone/edit/" + item.PhoneId + "' id='" + item.PhoneId + "' title='Edit'> <span class='glyphicon glyphicon-edit'> </span> </a>")
#Html.Raw("<a data-modal='' href='/phone/delete/" + item.PhoneId + "' id='" + item.PhoneId + "' title='Delete'> <span class='glyphicon glyphicon-trash'> </span> </a>")
</text>)
));
}
</div>
}
</div>
<!-- modal placeholder-->
<div id='myModal' class='modal fade in'>
<div class="modal-dialog">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
#section scripts{
#Scripts.Render("~/scripts/appjs/phones.js")
}
and the _partial view which will be rendered as a modal popup:-
#model SkillManagementTDMGroup.Models.Phone
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title">Edit Phone</h3>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.HiddenFor(m=>m.PhoneId)
<div class="modal-body">
//code goes here...
<input class="btn btn-primary" type="submit" value="Save" />
<button class="btn btn-warning" data-dismiss="modal">Close</button>
</div>
}
<script>
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
</script>
and here is the phones.js:-
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
var isValid = true; // assume all OK
$('form').validate(); // perform validation on the form
$('input[type="text"]').each(function (index, item) { // could change selector to suit e.g $('input, textarea').each(..
if (!$(this).valid()) {
isValid = false; // signal errors
return false; // break out of loop
}
})
if (!isValid) {
return false; // exit
}
$('#progress').show();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
$('#progress').hide();
//location.reload();
alert(result.message);
} else {
$('#progress').hide();
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
});
}
now when i visit the main view the modal popup will work well, but if i do some paging inside the webgrid and i click to render the partial view as modal popup i will get the following exception :-
Unhandled exception at line 51, column 9 in http://localhost:58652/phone/edit/3
0x800a1391 - JavaScript runtime error: '$' is undefined
on the following Script section inside the partial view:-
<script>
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
</script>
This issue is fixed and worked fine for me....
"Modal Popup will not show if i do ajax-based paging inside my WebGrid"
OR
"When navigate to 2nd page and click on edit, delete or view it is displaying normal page instead of displaying it in modal pop up".
Change code in phones.js:
From
$("a[data-modal]").on("click", function (e) {
To
$(document).on("click","a[data-modal]", function (e) {
Enjoy coding................
I want to call jquery function on Modal popup submit button, which is in partial view but the function is not called if that button is in partial view, it is only called when i put my modal pop up in main view. How to solve this issue... Please help .. Thanks
Index.cshtml
#Html.ActionLink("Create", "Create", null, null, new { id = "btnCreate", #class = "btn btn-small btn-info" })
<script type="text/javascript">
$(function () {
$.ajaxSetup({ cache: false });
$('#btnCreate').click(function () {
alert("function called");
$('.modal-dialog').load(this.href, function () {
$('#ShowModalDialog').modal({
backdrop: 'static',
keyboard: true
}, 'show');
});
return false;
});
});
</script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
$('#Useremail').blur(function () {
alert("func called");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home/Search',
data: "{'searchString':'" + document.getElementById('Useremail').value + "'}",
async: false,
success: function (response) {
alert("Record found");
},
error: function () { alert("record not found"); }
});
});
});
</script>
<div id='ShowModalDialog' class='modal fade in'>
<div class='modal-dialog'>
</div>
</div>
</body>
</html>
_Create.cshtml PartialView
#model MvcTwitterBootstrap.Models.UserDetail
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×</button>
<h3 id="myModalLabel">
Registration</h3>
</div>
#using (Html.BeginForm("Create", "Home", FormMethod.Post, new { #class = "modal-form" }))
{
#Html.ValidationSummary()
<div class="modal-body">
<div>
#Html.LabelFor(x => x.UserEmail)
#Html.TextBoxFor(x => x.UserEmail, new { #id = "Useremail" })
#Html.ValidationMessageFor(x => x.UserEmail)
</div>
<div>
#Html.LabelFor(x => x.UserPassword)
#Html.TextBoxFor(x => x.UserPassword, new { id = "Userpassword" })
#Html.ValidationMessageFor(x => x.UserPassword)
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">
Cancel</button>
<button class="btn btn-primary" type="button" id="btnsubmit">
Save</button>
</div>
}
</div>
for items that are added to the form after load you need to put the function on the document instead of the item
$(document).on('click', '#btnCreate', function(){
//code
});
the other option would be to put all of the click events in a function
function LoadScript(){
//jquery code here
}
and then call that function after the partial is loaded
$('#divContent').html(result);
LoadScript();