modal popup from Controller .NET MVC - javascript

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

Related

Getting button Id and passing id to a model button id

I have a dynamic button, that has an attribute of Stepid. What i am trying to do
is capture that attribute when the button is clicked and pass the same attribute into my model and assign the StepId value as my button Id in the modal.
My button
<button class="btn btn-warning moveRecipeStep" id="blah" data-bind="attr: {'data-id': StepId, data_recipe_name: $parent.RecipeName}" data-toggle="modal" data-target="#moveRecipeReason">#Html.LocalisedStringFor(model => model.MoveToStageText)</button>
and my modal
<section id="hidden">
<div class="modal fade" id="moveReason" tabindex="-1" role="dialog" arial-labelledby="moveReasonLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="moveReasonLabel">What is the reason for the Step move?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body reasonDialog">
<form>
<div class="form-group">
#Html.LabelFor(model => model.ReasonText)
#Html.TextAreaFor(model => model.ReasonText, new { rows = 4, #class = "form-control", maxlength = "100", data_bind = "value: Reason" })
</div>
</form>
</div>
<div class="modal-footer">
<button id="DoMove" type="button" class="btn btn-primary">#Html.LocalisedStringFor(model => model.SubmitText)</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="moveRecipeReason" tabindex="-1" role="dialog" arial-labelledby="moveReasonLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="moveReasonLabel">What is the reason for the Recipe move?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body reasonDialog">
<form>
<div class="form-group">
#Html.LabelFor(model => model.ReasonText)
#Html.TextAreaFor(model => model.ReasonText, new { rows = 4, #class = "form-control", maxlength = "100", data_bind = "value: Reason" , id = "blah" })
</div>
</form>
</div>
<div class="modal-footer">
<button id="DoMoveRecipe" type="button" class="btn btn-primary">#Html.LocalisedStringFor(model => model.SubmitText)</button>
</div>
</div>
</div>
</div>
</section>
And my javascript
var input = $(this);
var buttonId = input.attr("id");
var id = input.data("id");
var url = buttonId === 'MoveNext' ? '#Url.Action("MakeNext")' : '#Url.Action("MoveRecipePosition")';
$("#moveReason").modal("toggle");
if (buttonId === "MoveNext") {
$.ajax(url,
{
data: {
"Id": id,
"Reason": $("#moveReason .reasonDialog textarea").val(),
},
cache: false,
method: "POST",
}).done(function(returnData) {
if (returnData) {
if (returnData.BrokenRule !== null) {
alert(returnData.BrokenRule.Message);
} else if (returnData.ProcessStep !== null) {
var bFound = false;
//Done like this because you can only move backwards. Originally the logic was fuller but, most things don't change now.
//The extra logic just hides everything past the active one
for (var pos = 0; pos < viewModel.Stages().length; pos++) {
if (bFound) {
viewModel.Stages()[pos].Id(-1);
viewModel.Stages()[pos].IsNext(false);
} else if (viewModel.Stages()[pos].Id() == returnData.ProcessStep.Id) {
viewModel.Stages()[pos].IsNext(returnData.ProcessStep.IsNext);
viewModel.Stages()[pos].BenchId(returnData.ProcessStep.BenchId);
viewModel.Stages()[pos].BenchName(returnData.ProcessStep.BenchName);
viewModel.Stages()[pos].IsTransacted(returnData.ProcessStep.IsTransacted);
viewModel.Stages()[pos].RecipeName(returnData.ProcessStep.RecipeName);
bFound = true;
}
}
}
}
}).fail(function(xhr) {
try {
console.log(xhr.statusText);
console.log(xhr.responseText);
alert(xhr.statusText + "\r\n" + xhr.responseText);
} catch (ex) {
console.log(ex);
alert(ex);
}
});
} else {
$.ajax(url,
{
data: {
"SerialNumber": viewModel.SerialNumber(),
"Message": $("#moveRecipeReason .reasonDialog textarea").val(),
"StepId": a
},
cache: false,
method: "POST"
}).done(function(returnData) {
if (returnData) {
if (returnData.BrokenRule !== null) {
alert(returnData.BrokenRule.Message);
} else if (returnData.recipePosition !== null) {
var bFound = false;
//Done like this because you can only move backwards. Originally the logic was fuller but, most things don't change now.
//The extra logic just hides everything past the active one
for (var pos = 0; pos < viewModel.Stages().length; pos++) {
if (viewModel.Stages()[pos].RecipeName() !==
returnData.recipePosition.RecipeName)
continue;
for (var innerPos = 0;
innerPos < viewModel.Stages()[pos].RecipeStages().length;
innerPos++) {
var recipeStage = viewModel.Stages()[pos].RecipeStages()[innerPos];
if (bFound) {
recipeStage.StepId(-1);
recipeStage.IsNext(false);
} else if (viewModel.Stages()[pos].Id() === returnData.ProcessStep.Id) {
recipeStage.StepId(-1);
recipeStage.IsNext(true);
bFound = true;
}
}
}
}
}
}).fail(function(xhr) {
try {
console.log(xhr.statusText);
console.log(xhr.responseText);
alert(xhr.statusText + "\r\n" + xhr.responseText);
} catch (ex) {
console.log(ex);
alert(ex);
}
});
}
})
});
If anyone can give me some guidance, that much be much appreciated. Thank you very much.
It can be done simpler, here's an universal concept: How do you handle multiple submit buttons in ASP.NET MVC Framework?
Simple approach:
multiple submit button, same name (let it be abcd), different value
inside .NET controllers postback function have a string name (so string abcd) input parameter, where you check the value

How to pass a parameter to a modal form using Ajax

I have a razor page that displays a list of expenses for the Report selected. I have an "Add Expense" button on the page that brings up a modal. The modal is a partial View of the form. What i need to do is pass the ExpenseId to the modal. I can get the Id from the url like this
#{ var expenseId = Request.Url.Segments[3]; }
the button currently looks like this
<button type="button" data-toggle="modal" data-target="#expenseModal_#expenseId" data-id="#expenseId" class="btn btn-primary" id="addExpenses">
Add Expense
</button>
There are a few things in this that i do not know if i even need them. I was trying different things.
Modal
<!-- MODAL -->
<div class="modal fade" id="expenseModal_#expenseId" tabindex="-1" role="dialog" aria-labelledby="expenseModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="expenseModalLabel"> Expences </h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div> <!-- MODEL HEADER-->
<div class="modal-body">
</div> <!-- MODAL BODY-->
</div>
</div>
Javascript
<script type="text/javascript">
$(document).ready(function () {
$("#addExpenses").click(function () {
$(".modal-body").html('');
$.ajax({
type: 'GET',
url: '#Url.Action("_ExpenseForm", "Admin")',
data: { type: $(this).attr("data-type") },
success: function (response) {
$(".modal-body").html(response);
$("#expenseModal").modal('show');
},
error: function () {
alert("Something went wrong");
}
});
});
});
</script>
The expense Id has to be inserted in the form so that when it is saved it saves it to the correct Expense report.
Controller actions
ExpensesDataAcessLayer objexpense = new ExpensesDataAcessLayer();
public ActionResult ExpenseReports()
{
return View(db.ExpenseReports.ToList());
}
public ActionResult Expenses(int ExpenseId)
{
return View(db.Expenses.Where(x => x.ExpenseId == ExpenseId).ToList());
}
public ActionResult _ExpenseForm()
{
CustomerEntities customerEntities = new CustomerEntities();
List<SelectListItem> categoryItem = new List<SelectListItem>();
ExpensesViewModel casModel = new ExpensesViewModel();
List<ExpenseTypes> expensetypes = customerEntities.ExpenseType.ToList();
expensetypes.ForEach(x =>
{
categoryItem.Add(new SelectListItem { Text = x.CategoryItem, Value = x.ItemCategoryId.ToString() });
});
casModel.ExpenseTypes = categoryItem;
return View(casModel);
}
Thanks for your help!
You can store expenseId into hidden field, like this
<input id="expenseId" name="expenseId" type="hidden" value="#Request.Url.Segments[3]">
Then you can get like this
$("#addExpenses").click(function () {
var expenseId = $("#expenseId").val();
// after code here
Updated
You can get expenseId like this
var expenseId = $(this).attr("data-id")
Then you can assign it to hidden field or anywhere in Model, Like this
<!-adding aditional input into HTML in MODEL-!>
<input id="expenseId" name="expenseId" type="hidden" value="">
<!- Javascript-!>
var expenseId = $(this).attr("data-id")
expenseId.val(expenseId );

Ajax Success does not render partial view

I have placed a partial view into a modal to update a password like so:
<div class="modal fade" id="modalPassword" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-body">
<div class="modal-content">
<div id="message"></div>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Change Password</h4>
</div>
<div class="modal-
<div id="passwordForm">
#{
#Html.Action("ChangePassword","Account");
}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
This is my partial view:
#model WebApplication1.Models.ViewModel.ChangeUserPassword
#{
Layout = null;
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<form id="form">
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset id="submitPasswordForm">
<div class="col_full">
#Html.LabelFor(model => model.OldPassword, htmlAttributes: new { #class = "capitalize t600" })
#Html.TextBoxFor(model => model.OldPassword, null, new { #class = "sm-form-control", id = "txtOldPassword" })
#Html.ValidationMessageFor(model => model.OldPassword)
</div>
<div class="col_full">
#Html.LabelFor(model => model.ChangedPassword, htmlAttributes: new { #class = "capitalize t600" })
#Html.TextBoxFor(model => model.ChangedPassword, null, new { #class = "sm-form-control", id = "txtChangedPassword" })
#Html.ValidationMessageFor(model => model.ChangedPassword)
</div>
<div class="col_full">
#Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { #class = "capitalize t600" })
#Html.TextBoxFor(model => model.ConfirmPassword, null, new { #class = "sm-form-control", id = "txtConfirmPassword" })
#Html.ValidationMessageFor(model => model.ConfirmPassword)
</div>
<div class="modal-footer">
<button type="button" class="btn btn-warning" data-dismiss="modal">Cancel</button>
<input type="submit" value="Save Changes" class="btn btn-primary" id="btn_save_password" />
</div>
</fieldset>
</form>
When I click the "btn_save_password", I invoke the onclick event like so:
$("#btn_save_password").click(function (event) {
event.preventDefault();
var data = $("#submitPasswordForm").serialize();
$.ajax({
type: "POST",
url: "#Url.Action("ChangePassword", "Account")",
data: data,
success: function (result) {
$("#passwordForm").empty();
//$("div").remove("#passwordForm");
addHtml(result);
},
error: function () {
$("#passwordForm").html("Error occured");
}
});
});
function addHtml(htmlString) {
$("#msg").html(htmlString);
}
Then it invokes a method in my controller "ChangePassword"
[Authorize]
public ActionResult ChangePassword()
{
return PartialView();
}
[HttpPost]
public ActionResult ChangePassword(ChangeUserPassword password)
{
if (ModelState.IsValid)
{
var cookie = HttpContext.Request.Cookies["Sys_user_id"];
var um = new UserManager();
if (cookie != null && um.GetAccountPassword(Convert.ToInt32(cookie.Value), password.OldPassword))
{
um.ChangeUserPassword(password, Convert.ToInt32(cookie.Value));
}
else
{
ModelState.AddModelError("","Wrong current password");
}
}
else
{
ModelState.AddModelError("","Error");
}
return View();
}
The "ChangePassword" method invokes the PartialView "ChangePassword.html" like so:
[Authorize]
public ActionResult ChangePassword {
return PartialView();
}
I can view the partial view on the modal and I am able to successfully update the database. But the problem is, I want to be able to send a successful message or error message into the modal when it is successful or not. Upon submission, whether it has updated the database or not, it refreshes the page and the modal is gone. I want to be able to get the message into the modal.
Your help is greatly appreciated.
EDIT --
I can now see the validation message in the Modal but it only works once. As soon as I click the "btn_save_password" again, the page refreshes.
Add two <div> sections containing your messages (Successs and Failed) with the hide class in the partial view. After Ajax Submission, Add class Show for the suitable div.
eg:
<div class="alert alert-danger text-center hide" role="alert"id="FailedMesssage">
Failed....!!!
</div>
<div class="alert alert-success text-center hide" role="alert" id="successMesssage">
success....!!!
</div>
<button type = "button" value="Submit" onclick ="Test()"/>
Set Var Value as 0 or 1 using ajax code then try following script
<script>
function Test()
{
var value =1;
if(value == 1)
{
$("#successMesssage").addClass("show").removeClass("hide");
}
else
{
$("#FailedMesssage").addClass("show").removeClass("hide");
}
}
</script>

Why is the delete button on my application not working?

I made a delete button that's supposed to delete some entries from a model, but i keep getting an error that i'm not sure how to solve, I have a controller that has an IActionresult named deletelname, and everything seems logical but i just don't know why it's not working. If someone could look at the code and give me some feed back i would appreciate it very much.
The view:
#model IEnumerable<Models.pinfo>
#using Models
#foreach (var s in Model){
<h1> #s.fname #s.lname </h1> <h3> #s.comment </h3> <a class="GoDelete" href="javascript:void(0)" data-id="#s.lname">Delete</a>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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">Deleting....</h4>
</div>
<div class="modal-body">
Are you sure to Delete this Course?
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="btndelete" type="button" class="btn btn-primary">Delete</button>
</div>
</div>
</div>
</div>
}
#section scripts
{
<script>
$(document).ready(function() {
$("#btndelete").click(function () {
$('#myModal').modal('hide');
var id = $('#hfId').val();
window.location.href = '#Url.Action("deletelname","Home")/'+id;
});
$(".GoDelete").click(function () {
var id = $(this).attr("data-id");
$('#hfId').val(id);
$('#myModal').modal('show');
});
});
</script>
}
the Controller piece:
public IActionResult deletelname(pinfo pinfo)
{
var fsname = db.pinfo;
var lsname = db.pinfo;
var csomment = db.pinfo;
foreach (var fname in fsname)
{
db.Remove(fname);
}
foreach (var lname in lsname){
db.Remove(lname);
}
return View("Contact", "Home");
}
here is the error i get when i press the delete button:
The error message is because you are passing the string "Home" as the model for the view "Contact". The view is expecting an enumerable object of type Model.pinfo
try passing the pinfo object back out of the controller when rendering the view. I'm not sure that will do what you want but it seems to be what you are looking for.
public IActionResult deletelname(pinfo pinfo)
{
var fsname = db.pinfo;
var lsname = db.pinfo;
var csomment = db.pinfo;
foreach (var fname in fsname)
{
db.Remove(fname);
}
foreach (var lname in lsname){
db.Remove(lname);
}
return Contact();
}
Javascript is not correct either
$("#btndelete").click(function () {
$.ajax({
url: '#Url.Action("deletelname","Home")',
method: 'POST',
data: { pinfo: $('#hfId').val() },
success: function (response) {
// this code gets run after the request is successful
// based on the controller method that we have written, the response
// should be all of the "Contact" view html re-rendered.
console.log(response);
//if there is an error you will probably not want to close the modal
// so only close if it is successful
$('#myModal').modal('hide');
},
error: function (response) {
//runs if there is an error
console.log(response);
}
});
});

Ajax post request not passing through ID

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

Categories

Resources