Razor: button click not fired correctly - javascript

I have a view. I want to load it to get all information then click Edit or Delete button to do something. When click Edit button then I hope it goes to another view.
#model Models.CountryLanguagesModel
#{
ViewBag.Title = "Language";
}
<div class="span4 proj-div text-center" data-toggle="modal" data-target="#addLanguageModal">
<u>Add Language</u>
<div><br /> </div>
<table class="table table-bordered table-dark-header table-responsive">
<tr>
<th class="text-center">Language Name</th>
<th class="text-center">Welcome Message</th>
<th></th>
</tr>
#foreach (var item in Model.CountryLanguages)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.LanguageName)</td>
<td>#Html.DisplayFor(modelItem => item.WelcomeMessage)</td>
</tr>
}
</table>
</div>
<div class="container">
<div class="col-md-8 col-md-offset-2">
<button class="btn btn-success" id="editLanguage">Edit</button>
<button class="btn btn-danger" id="deleteLanguage">Delete</button>
</div>
</div>
<div class="modal fade" id="addLanguageModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Add Language</h3>
</div>
<div class="modal-body">
<div class="form-group">
</div>
<div class="form-group">
<div class="left">
<label>Language Name:</label>
</div>
<div class="right">
<input type="text" class="form-control" name="languageName" id="languageName" />
</div>
</div>
<div class="form-group">
<div class="left">
<label>Welcome Messagee:</label>
</div>
<div class="right">
<input type="text" class="form-control" name="welcomeMessage" id="welcomeMessage" />
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-gray" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary" id="addLanguageBtn">Save</button>
</div>
</div>
</div>
</div>
#section scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#addLanguageBtn").on("click", function (evt) {
var CountryId = #Model.CountryId;
var languageName = $("#languageName").val();
var welcomeMessage = $("#welcomeMessage").val();
$.post("/Country/AddLanguage", { id: CountryId, languageName: languageName, welcomeMessage: welcomeMessage }, function (data) {
$("#languageName").val("");
$("#welcomeMessage").val("");
$("#addLanguageModal").modal('hide');
});
});
$("#editLanguage").on("click", function (evt) {
var CountryId = #Model.CountryId;
$.post("/Country/LanguageEdit", { id: CountryId }, function () {
});
});
$("deleteLanguage").on("click", function (evt) {
var CountryId = #Model.CountryId;
$.post("/Country/LanguageDelete", { id: CountryId }, function () {
});
});
});
</script>
}
Now the question is when the page loaded, I found the the code reached click event script. It is strange. When I click the button, it doesn't reach the script. But it goes to the controller action method,
[HttpPost]
public ActionResult LanguageEdit(MyModel model)
{
I guess some stupid error to cause the onclick event not fired correctly, but I can't figure it out.
EDIT
public ActionResult LanguageEdit(int id)
{
var model = new CountryLanguageModel();
model.CountryId = id;
model.CountryLanguageQuestion = MyService.GetQuestion(x => x.CountryId == id);
return View(model);
}

Add type='button' attribute to your buttons, if not it will behave as a submit button.

can you change button to a ?
<button class="btn btn-success" id="editLanguage">Edit</button>
to
<a href="/Country/LanguageEdit?id=#Model.CountryId" class="btn btn-success" />
Some more information
if you want to GET somekind of HTML use HTTPGET instead of HTTPPOST.
Use HTTPPOST if you want to send some kind of information, that server should for example save. Use HTTPGET if you want to render some kind of view ( for example get a new view),
Your Action required 'MyModel model' not a id.

As per your comment you may get this behaviour:
why it was fired when page loaded, I didn't click the button at all.
When your javascript code not inside the button click event and instead it is inside any of the other event such document ready or page load ..etc.
So kindly check the event of javascript and surely you will get the direction to solution .
After checked ,If you ,still had the same problem. kindly show us your javascript so that it will be useful to help you further
Thanks
Karthik

Related

Asp Validations inside a modal

I am working on creating Modal pop-ups for CRUD operations. I have created working modals for Create and Edit. My issue is now I have no way to use the validations from the server side which I need to have. When Edit fails the validation test it rightfully so rejects the request but redirects back to the Edit view in a non modal form. Please see below.
Modal:
After Invalid input:
I believe its going into the controller post edit and rendering from the URL. Which its good as it gives the validation for the pin being empty correctly, However this would need to be rendered on the Modal Edit 1234 pop up. Will include Model, controller , index view, Edit view, and js to help with the issue. Thank you for your help.
Model:
public class Airmen
{
[Key]
[Required]
public string MobileID { get; set; }
[Required]
public string Pin { get; set; }
}
public class SuperModel
{
public Airmen airmen { get; set; }
public IEnumerable<Airmen> airmens { get; set; }
}
Controller:
public async Task<IActionResult> Index(SuperModel arm)
{
arm.airmens = await _context.Airmen.ToListAsync();
return View(arm);
}
[HttpGet]
public async Task<IActionResult> Edit(string id)
{
SuperModel airmen = new SuperModel();
airmen.airmen = await _context.Airmen.FindAsync(id);
return PartialView(airmen);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(string id, [Bind("MobileID,Pin")] Airmen airmen)
{
SuperModel amn = new SuperModel();
if (id != airmen.MobileID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(airmen);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!AirmenExists(airmen.MobileID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
amn.airmen = airmen;
return PartialView(amn);
}
Index View:
#model ALRSweb4.Models.SuperModel
#{ViewData["Title"] = "Index";}
<h1>Index</h1>
<table class="table">
<thead>
<tr>
<th>
Mobile ID
</th>
<th>
Pin
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.airmens)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.MobileID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Pin)
</td>
<td>
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#Edit" data-url="#Url.Action(item.MobileID,"Airmen/Edit")">
Edit
</button>
<a asp-action="Details" asp-route-id="#item.MobileID">Details</a> |
<a asp-action="Delete" asp-route-id="#item.MobileID">Delete</a>
</td>
</tr>
}
</tbody>
</table>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#CreateModal">
Create
</button>
<div class="modal fade" id="CreateModal" 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">Create</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#Html.Partial("Create")
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<div id="EditPlaceHolder">
</div>
Edit View:
#model ALRSweb4.Models.SuperModel
#{
ViewData["Title"] = "Edit";
}
<div class="modal fade" id="Edit" 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">Edit 12343</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="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input asp-for="airmen.MobileID" />
<div class="form-group">
<label asp-for="airmen.Pin" class="control-label"></label>
<input asp-for="airmen.Pin" class="form-control" />
<span asp-validation-for="airmen.Pin" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
JS:
// t2
$(function () {
var CreatePlaceHolderElement = $('#EditPlaceHolder');
$('button[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
var decodedUrl = decodeURIComponent(url);
$.get(decodedUrl).done(function (data) {
CreatePlaceHolderElement.html(data);
CreatePlaceHolderElement.find('.modal').modal('show');
})
})
CreatePlaceHolderElement.on('click', '[data-save="modal"]', function (event) {
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.post(actionUrl, sendData).done(function (data) {
CreatePlaceHolderElement.find('.modal').modal('hide');
location.reload(true);
})
})
})
// end of t2
// start of function for create modal
$(function () {
var CreatePlaceHolderElement = $('#CreatePlaceHolder');
$('button[data-toggle="ajax-modal"]').click(function(event){
var url = $(this).data('url');
$.get(url).done(function (data) {
CreatePlaceHolderElement.html(data);
CreatePlaceHolderElement.find('.modal').modal('show');
})
})
CreatePlaceHolderElement.on('click', '[data-save="modal"]', function (event) {
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.post(actionUrl, sendData).done(function (data) {
CreatePlaceHolderElement.find('.modal').modal('hide');
location.reload(true);
})
})
})
// end of function for create modal
Html.RenderPartialAsync cannot render the js successfully by ajax call back. So the fastest way is to add the js in Edit view like below and it will prevent form submit:
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
The ajax function below is useless, just remove the following code to use default form submit. The reason for why removing it is because firstly your code does not have any element with data-save="modal". Then you have <input type="submit" /> which will submit your form data by default without using ajax.
CreatePlaceHolderElement.on('click', '[data-save="modal"]', function (event) {
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.post(actionUrl, sendData).done(function (data) {
CreatePlaceHolderElement.find('.modal').modal('hide');
location.reload(true);
})
})

Adding Dynamic buttons to display pop-up window to link entries

I am creating a list of entries each with a Link button in a foreach loop on my Razor Page. The Link button is clicked to open a modal with another list of entries and all of these entries have a checkbox. This view allows me to Link an entry to multiple other entries. Code below for HTML:
#foreach (var entry in Model.EntryList.Where(w => w.IsLinked == false))
{
<tr>
<td class="pt-3-half" contenteditable="true">#entry.Description</td>
<td class="pt-3-half" contenteditable="true">
<button id="btnShowModal" type="button" class="btn btn-sm btn-default pull-left col-lg-11 button button4">
Link
</button>
<div class="modal fade" tabindex="-1" id="loginModal"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Link Entries</h4>
<button type="button" class="close" data-dismiss="modal">
×
</button>
</div>
<form enctype="multipart/form-data" asp-controller="Home" asp-action="Index" asp-route-id="#entry.Description" method="post" class="mt-3">
<div class="modal-body">
<table style="text-align: center; width: 100%">
<thead>
<tr>
<th class="text-center">Description</th>
<th class="text-center"></th>
</tr>
</thead>
<tbody>
#foreach (var LinkEntry in Model.EntryList.Where(w => w.IsLinked == true))
{
<tr>
<td class="pt-3-half" contenteditable="true">#LinkEntry.Description</td>
<td class="pt-1-half" contenteditable="true">
<input name="AreChecked" type="checkbox" value="#LinkEntry.Id" />
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4">Link Entries</button>
<button type="button" id="btnHideModal" class="btn btn-primary button button4">
Hide
</button>
</div>
</form>
</div>
</div>
</div>
</tbody>
</table>
</div>
</td>
</td>
</tr>
}
When the Link button is clicked the below jQuery runs:
<script type="text/javascript">
$(document).ready(function () {
$("#btnShowModal").click(function () {
$("#loginModal").modal('show');
});
$("#btnHideModal").click(function () {
$("#loginModal").modal('hide');
});
});
</script>
The current problem I have is that only the first Link button shows the Modal div. The rest of the Link buttons do not do anything when clicked. So I then moved the entire Modal Div outside of the foreach but does not fix the problem and this then also doesn't allow me to parse the asp-route-Id due to now being outside the foreach.
The issue here is that you are using hard-coded ids for your buttons, but they are created in a loop so more than one element with the same id is created, which you definitely do not want.
Remove the ids and replace them with a unique class, like btn-show-modal, then change your jquery selector from $("#btnShowModal") to $(".btn-show-modal").
Do the same thing with your hide buttons, but use a different unique class name like btn-hide-modal. Be sure to do this with all hard-coded ids (looks like there is at least one more instance).
One other point I should make is you will need to query the modal relative to the button that is clicked. Inside the click events, you should do $(this).next().modal('show') / $(this).next().modal('hide') , since as stated, you need to remove the id="loginModal" and will need an alternative method to get the correct modal to show.
I believe jquery is smart enough to not search the entire DOM when using the id selector (#), so that is why only your first button is firing your click event.
My suggestion to future proof these kinds of errors is to create a <script> that will search the DOM for duplicate ids and show an alert(), or something, to let you know that your DOM is invalid. I'd also make sure that this script is only added when debugging, as with this <script> you will catch the errors during development and do not want to the extra overhead in production.
Yes as William says, you have that error because you are using an id and that button is being created so many times as items you have in your collection. And if I was you I'll put the modal outside the first loop because otherwise you can create a lot of modal too. I leave you an example of something that I hope can help you.
This is the model:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace HelloWorldMvcApp
{
public class SampleViewModel
{
[Required]
[MinLength(10)]
[MaxLength(100)]
[Display(Name = "Ask Magic 8 Ball any question:")]
public string Question { get; set; }
//See here for list of answers
public string Answer { get; set; }
public List<Test> EntryList { get; set; }
}
public class Test {
public int Id { get; set; }
public string Description { get; set; }
public bool IsLinked { get; set; }
}
}
Here you are the controller:
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
var list = new SampleViewModel();
list.EntryList = new List<Test>();
var test1 = new Test();
test1.Id = 1;
test1.Description = "test1";
test1.IsLinked = false;
list.EntryList.Add(test1);
var test2 = new Test();
test2.Id = 2;
test2.Description = "test2";
test2.IsLinked = false;
list.EntryList.Add(test2);
var test3 = new Test();
test3.Id = 3;
test3.Description = "test3";
test3.IsLinked = false;
list.EntryList.Add(test3);
var test11 = new Test();
test11.Id = 11;
test11.Description = "test11";
test11.IsLinked = true;
list.EntryList.Add(test11);
var test12 = new Test();
test12.Id = 12;
test12.Description = "test12";
test12.IsLinked = true;
list.EntryList.Add(test12);
var test21 = new Test();
test21.Id = 21;
test21.Description = "test21";
test21.IsLinked = true;
list.EntryList.Add(test21);
var test22 = new Test();
test22.Id = 22;
test22.Description = "test22";
test22.IsLinked = true;
list.EntryList.Add(test22);
return View(list);
}
}
}
And this is the view.
#model HelloWorldMvcApp.SampleViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<table>
<tbody>
#foreach (var entry in Model.EntryList.Where(w => w.IsLinked == false))
{
<tr>
<td class="pt-3-half" contenteditable="true">#entry.Description</td>
<td class="pt-3-half" contenteditable="true">
<button type="button" onClick="showModal('#entry.Description')" class="btn btn-sm btn-default pull-left col-lg-11 button button4">
Link
</button>
</td>
</tr>
}
</tbody>
</table>
<div class="alert alert-warning fade">
<img src="http://entechprod.blob.core.windows.net/dotnetfiddle/morpheus.jpg"
style="max-width:100%;" /><br /><br />
<strong><span class="alert-content"></span></strong>
</div>
</div>
</div>
<div class="modal fade" tabindex="-1" id="loginModal" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Link Entries</h4>
<button type="button" class="close" data-dismiss="modal">
×
</button>
</div>
<form enctype="multipart/form-data" id="modalForm" asp-controller="Home" asp-action="Index"
asp-route-id="" method="post" class="mt-3">
<div class="modal-body">
<table style="text-align: center; width: 100%">
<thead>
<tr>
<th class="text-center">Description</th>
<th class="text-center"></th>
</tr>
</thead>
<tbody>
#foreach (var LinkEntry in Model.EntryList.Where(w => w.IsLinked == true))
{
<tr>
<td class="pt-3-half" contenteditable="true">#LinkEntry.Description</td>
<td class="pt-1-half" contenteditable="true">
<input name="AreChecked" type="checkbox" value="#LinkEntry.Id" />
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary button button4">Link Entries</button>
<button type="button" onClick="hideModal()" class="btn btn-primary button button4">
Hide
</button>
</div>
</form>
</div>
</div>
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
function showModal(desc) {
$('#modalForm').attr('asp-route-id', desc);
$("#loginModal").modal('show');
}
function hideModal(desc) {
$("#loginModal").modal('hide');
}
</script>
</body>
</html>
Creating a modal for each entry in the loop seems unnecessary to me,
Create a single modal outside your loop and update all its data according with the Link button you clicked
Use data- attributes to pass the info you require to the click event and to build/update your modal, you can JSON your info and use a javascript function to create the table and checkboxes bit
#foreach (var entry in Model.EntryList.Where(w => w.IsLinked == false))
{
<tr>
<td class="pt-3-half" contenteditable="true">#entry.Description</td>
<td class="pt-3-half" contenteditable="true">
<button data-entry-id="#entry.Id" data-entries="<?= htmlentities(json_encode(Model.EntryList.Where(w => w.IsLinked == true)))?>" id="btnShowModal" type="button" class="btn btn-sm btn-default pull-left col-lg-11 button button4 ">
Link
</button> ...
then you add a listener with JS to all those Link buttons
function onClickLinkButtonUpdateModal($e){
let entries = JSON.parse($e.target.dataset.entries);
let entry_id = $e.target.dataset.entryId;
//pass the info you need, you can create the tr elements or the whole tbody with document.create or with template literals
let tr_entries = generateHTMLEntries(entry_id, entries);
//assuming you put an id to the table or the table body
document.querySelector('#modal-table').appendChild(tr_entries);
//or
//document.querySelector('#modal-tbody').innerHTML = tr_entries;
}

How to submit form in jquery

This maybe a simple problem, but I can't find the cure.
When I executes this :-
$('#save_results').on("click", function () {
$('#formSaveQuotationPrepDetail').submit();
});
Everything works fine. But when I do this :-
$('#save_results').on("click", function () {
$('#formSaveQuotationPrepDetail').submit(function (e) {
var result = '#TempData["StatusMsg"]';
e.preventDefault();
if (result == 'Success') {
alert("Saved Successfully.");
}
})
});
This is my code behind :-
[HttpPost]
public ActionResult SaveQuotePreparation(QuotationPreparationEntity quoteP)
{
string result = objManager.SaveQuotePreparation(quoteP);
if (!string.IsNullOrEmpty(result) && (result == GeneralConstants.Inserted || result == GeneralConstants.Updated))
{
//Payment Gateway
data = GeneralConstants.SavedSuccess;
TempData["StatusMsg"] = "Success";
}
return new JsonResult { Data = data, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
My HTML is a long code , I've made it short just for understanding :-
#using (Html.BeginForm("SaveQuotePreparation", "Technical", FormMethod.Post, new { #id = "formSaveQuotationPrepDetail" }))
{
<div class="row">
<form>
<div class="col-md-12 text-left">
<div class="row text-center">
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label ">
Quote Number
</label>
#Html.DropDownListFor(m => m.QuoteNo, new SelectList(#ViewBag.ListQuoteNo, "DataStringValueField", "DataTextField", Model.QuoteNo),
new
{
#class = "form-control requiredValidation",
#id = "QuoteNo",
#data_inneraction = "validationCall",
#onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)"
})
<span class="HideValidMsg">Please Select QuoteNo</span>
</div>
</div>
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label">
Product Line
</label>
#Html.DropDownListFor(m => m.ProductLine, new SelectList(#ViewBag.ListProdGrp, "DataStringValueField", "DataTextField", Model.ProductLine),
new
{
#class = "form-control requiredValidation",
#id = "ProductLine",
#onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)",
ng_model = "ProductLine",
ng_change = "GetProductLineDetails(ProductLine)"
})
<span class="HideValidMsg">Please Select ProductLine</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 pt-4 text-center">
<button type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results">Save</button>
#*<input style="font-size:18px" type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results" value="Save" />*#
<input style="font-size:18px" type="button" class="btn btn-secondary btn-sm" data-dismiss="modal" value="Close" />
</div>
</div>
</form>
The Event don't fire on click. I don't get any error or anything.
I want to return JSON data on submit and show it as an alert on the screen.
You can do form submit in javascript like this..
$(document).on("submit", "form", function (event) {
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status) {
successFunction()
}
},
error: function (xhr, desc, err) {
}
});
});
The From will define like this
<form class="form-horizontal" id="frm" name="frm" action="/Controler/Action" method="post" enctype="multipart/form-data"></form>
And Need to create the button as submit
<input type="submit"/>
i dont have your html code but ,
if you want your form to be submitted by on click event :
$('#save_results').on("click", function () {
e.preventDefault();
$('#formSaveQuotationPrepDetail').submit();
if (result == 'Success') {
alert("Saved Successfully.");
}
});
take a look at this example to see difference between your first and second code .
NOTE : in your code result is not defined , i am not sure where have you brought it from
You did mistake in view page. Please remove <form> tag inside view page. It will work.
You only use below code instead of your code:
note: Html.Beginform() method work as tag in HTML
#using (Html.BeginForm("SaveQuotePreparation", "Technical", FormMethod.Post, new { #id = "formSaveQuotationPrepDetail" }))
{
<div class="row">
<div class="col-md-12 text-left">
<div class="row text-center">
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label ">
Quote Number
</label>
#Html.DropDownListFor(m => m.QuoteNo, new SelectList(#ViewBag.ListQuoteNo, "DataStringValueField", "DataTextField", Model.QuoteNo), new { #class = "form-control requiredValidation", #id = "QuoteNo", #data_inneraction = "validationCall", #onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)" })
<span class="HideValidMsg">Please Select QuoteNo</span>
</div>
</div>
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label">
Product Line
</label>
#Html.DropDownListFor(m => m.ProductLine, new SelectList(#ViewBag.ListProdGrp, "DataStringValueField", "DataTextField", Model.ProductLine), new { #class = "form-control requiredValidation", #id = "ProductLine", #onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)", ng_model = "ProductLine", ng_change = "GetProductLineDetails(ProductLine)" })
<span class="HideValidMsg">Please Select ProductLine</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 pt-4 text-center">
<button type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results">Save</button>
#*<input style="font-size:18px" type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results" value="Save" />*#
<input style="font-size:18px" type="button" class="btn btn-secondary btn-sm" data-dismiss="modal" value="Close" />
</div>
</div>
</div>
}

Passing "Id" selected checkbox to Modal bootstrap and send to controller

I have a list of Articles and I want to have a possibility to delete selected articles or all articles in a modal popup window. Also, I have checkboxes in my View. My idea - get an "Id" of each selected article, passing these articles to modal bootstrap popup. After, using form-action Post will send these "Id" to action controller method for further actions. (public ActionResult DeleteArticle (FormCollection fc){}).
I want to understand how I can pass "Id" of selected with checkboxes Articles to modal Bootstrap popup. Thanks!
My ListOfArticls.cshtml:
<table class="table table-striped table-hover">
<thead>
<tr>
<th>
<span class="custom-checkbox">
<input type="checkbox" id="checkBoxAll">
<label for="selectAll"></label>
</span>
</th>
<th>#Html.DisplayNameFor(model => model.Title)</th>
<th>#Html.DisplayNameFor(model => model.PublishDate)</th>
<th>#Html.DisplayNameFor(model => model.Tag)</th>
<th>#Html.DisplayNameFor(model => model.Note)</th>
<th>#Html.DisplayName("Category name")</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<span class="custom-checkbox">
<input type="checkbox" class="chkCheckBoxId" value="#item.Id">
<label for="chkCheckBoxId"></label>
</span>
</td>
<td>
#Html.ActionLink(Html.DisplayFor(modelItem => item.Title).ToHtmlString(), "ArticleDetails", new { id = item.Id })
</td>
<td>
#Html.DisplayFor(modelItem => item.PublishDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Tag)
</td>
<td>
#Html.DisplayFor(modelItem => item.Note)
</td>
<td>
#Html.DisplayFor(modelItem => item.Category.Name)
</td>
<td>
<i class="material-icons" data-toggle="tooltip" title="Edit"></i>
<i class="material-icons" data-toggle="tooltip" title="Delete"></i>
</td>
</tr>
}
</tbody>
</table>
<script type="text/javascript">
$(document).ready(function () {
$('#checkBoxAll').click(function () {
if ($(this).is(":checked")) {
$(".chkCheckBoxId").prop("checked", true)
}
else {
$(".chkCheckBoxId").prop("checked", false)
}
});
});
</script>
Popup:
<!-- Delete Modal HTML -->
<div id="deleteArticleModal" class="modal fade">
<div class="modal-dialog">
<input type="hidden" id="linkId" />
<div class="modal-content">
<form action="#Url.Action("DeleteArticle", "Post")" method="post">
<div class="modal-header">
<h4 class="modal-title">Delete Employee</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<p>Are you sure you want to delete these Records?</p>
<p class="text-warning"><small>This action cannot be undone.</small></p>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Cancel" onclick="deleteConfirm()">
<input type="submit" class="btn btn-danger" value="Delete">
</div>
</form>
</div>
</div>
</div>
Controller:
[HttpPost]
public ActionResult DeleteArticle(FormCollection fc)
{
// Some code
return RedirectToAction("ListOfArticles");
}
UPDATE:
Little bit corrected:
js
// loop through all the check boxes
$("input[type=checkbox]:checked").each(function () {
and my controller:
[HttpPost]
public ActionResult DeleteArticle(FormCollection fc)
{
var values = fc["articlesArray"];
string[] str = values.Split(',');
for(int i=0; i < str.Length; i++)
{
postService.DeleteArticleDTO(Int32.Parse(str[i]));
}
return RedirectToAction("ListOfArticles");
}
If I understand this correctly, you want to multi-select through check boxes and clicking "Delete" on any of the row's delete buttons will open the popup with the ID's of the selected articles.
You got this part correct; the checkbox input field with ID as its value.
<input type="checkbox" class="chkCheckBoxId checkbox" value="#item.Id">
Next what we want to do is loop through all the check boxes whenever the delete button is clicked.
During the loop, we will identify which ones are checked and add them to the form tag of your modal.
Add the new script below to your code, read the comments as well.
<script type="text/javascript">
$(document).ready(function () {
$('#checkBoxAll').click(function () {
if ($(this).is(":checked")) {
$(".chkCheckBoxId").prop("checked", true)
}else{
$(".chkCheckBoxId").prop("checked", false)
}
});
// bind this event to all delete buttons
$(".delete").click(function(){
// find the modal body
var modal = $("#deleteArticleModal").find(".modal-body");
// loop through all the check boxes (class checkbox)
$(".checkbox").each(function(index){
// if they are checked, add them to the modal
var articleId = $(this).val();
if($(this).is(":checked")){
// add a hidden input element to modal with article ID as value
$(modal).append("<input name='articlesArray' value='"+articleId+"' type='hidden' />")
}
});
});
});
</script>
In your form collection, the values will be passed with the property name articlesArray. It will be an array so be sure to loop through it with foreach.

how to refresh and rebind the data from db in angularjs

hi all iam using angularjs ngrepeat to bind the datas into table.i have one add new button when i click bootstrap model popup open i fill the input details click submit means data will stored correctly but table couldn't not get the new data but once i reload the page data will show
my controller code
var refresh = function () {
$http.get('/ViewFacility').success(function (response) {
$scope.ViewFacilitys = response;
};
refresh();
My add new code:
$scope.AddRole = function () {
$http.post('/AddNewRole', $scope.Role).success(function (response) {
refresh();
});
};
Html Code
<form name="profileform">
<div class="modal fade" id="myModal" role="dialog" ng-controller="IndexController">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" style="margin-top:135px">
<div class="modal-header">
<h4 class="modal-title ">Role Name</h4>
</div>
<div class="modal-body">
<h4>Name</h4>
<input type="text" name="RoleName" class="form-control" ng-model="Role.RoleName">
<span class="error" ng-show="profileform.FirstName.$invalid && profileform.FirstName.$dirty">Please enter a First Name</span>
<h4>Description</h4>
<input type="text" name="Description" class="form-control" ng-model="Role.Description">
<span class="error" ng-show="profileform.LastName.$invalid && profileform.LastName.$dirty">Please enter a Last Name</span>
<h4>IsActive</h4>
<input type="checkbox" name="IsActive" class="form-control checkbox" ng-model="Role.IsActive" style="margin-left:-47%" >
<span class="error" ng-show="profileform.Email.$invalid && profileform.Email.$dirty">Please enter a Email</span>
</div>
<div class="modal-footer">
<button class="btn btn-primary" ng-click="AddRole()" ng-disabled="profileform.$invalid">Submit</button>
<button class="btn btn-primary" data-dismiss="modal" ng-click="deselect()">Clear</button>
</div>
</div>
</div>
</div>
</form>
Just add the new item to the array.
$scope.AddRole = function () {
$http.post('/AddNewRole', $scope.Role).success(function (response) {
$scope.ViewFacilitys.push($scope.Role);
});
};
You don't need to fetch all data each time you create a new item. Refresh must be called just one time.
For pagination you can code a simple function that send the number of page to the server:
$scope.changePage = function (page) {
$scope.get('/ViewFacility?page='+page)
.then(function (response) {
$scope.ViewFacilitys = response.data;
});
}
Try modifying your refresh function like so
var refresh = function () {
$http.get('/ViewFacility').success(function (response) { //assuming this only fetches the newly added one
$scope.ViewFacilitys.push(response);
};

Categories

Resources