I have the following program with a submit form and a javascript part, which should reset my textboxes, but after submitting nothing happens.
<div class="row">
<div class="col-md-4">
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<table>
<tr>
<td>#Html.Label("Name")</td>
<td>#Html.TextBox("name", null, new { id = "tb1" })</td>
</tr>
<tr>
<td>#Html.Label("Mail")</td>
<td>#Html.TextBox("mail", null, new { id = "tb2" })</td>
</tr>
</table>
<input type="submit" value="Send" onclick="clear" />
}
</div>
</div>
#section scripts {
<script type="text/javascript">
$(document).ready(function () {
});
function clear() {
$("#tb1").val("");
$("#tb2").val("");
}
</script>
}
Is there anything I´m missing? Any help is appreciated!
Related
**** Edit - Apparently this only happens on MS Edge. It works with a single Enter on Chrome and Firefox.**
I have a problem where a form is only submitted after I hit enter twice on a text box.
The form is extremely simple, just 1 text box and the submit button.
It all works fine if I explicitly hit the Submit button; data displays correctly and all, but I want to also submit by hitting enter. And I noticed that if i just hit enter once, it does not work. It isn't until I hit enter twice that the form actually submits.
I already tried binding to jquery's keypress, and even doing .live(), but even then it only works after hitting enter twice.
In case it's relevant, the reason I'm binding to DOMSubtreeModified on Search.cshtml is because I'm using the datatables.net jQuery plugin, and I could not find a way to call the .DataTable() method on the table after the form submits, so I had to call it after the HTML on the div changes.
My setup is as follows:
Search.cshtml
<div id="search-form">
#Html.Action("SearchForm", "Item")
</div>
<br />
<br />
<div id="search-results">
</div>
#section scripts {
<script type="text/javascript">
$('#search-results').bind("DOMSubtreeModified", function () {
$('#items').DataTable();
});
</script>
}
_SearchFormPartial.cshtml
#using (Ajax.BeginForm("Search", "Item", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "search-results"
}))
{
<div class="row">
<div class="col-md-3">
<input type="text" id="term" name="term" placeholder="Search by Item Name" class="form-control" autofocus />
</div>
<div class="col-md-2">
<input type="submit" value="Search" id="btnSearch" class="btn btn-default" />
</div>
</div>
}
_SearchResultsPartial.cshtml
#model List<MyItem>
#{
ViewBag.Title = "Search Results";
}
<table class="table table-striped" id="items">
<thead>
<tr>
<td><strong>Name</strong></td>
<td><strong>Type</strong></td>
<td><strong>Status</strong></td>
</tr>
</thead>
#foreach (var item in Model)
{
<tr class="clickable-row">
<td>#item.Name</td>
<td>#item.Type</td>
<td>#item.Status</td>
</tr>
}
</table>
#section scripts {
<script type="text/javascript">
$(document).ready(function () {
$("#items tr").css('cursor', 'pointer');
});
$("#items tr.clickable-row").on('click', function (e, row, $element) {
var url = $(this).closest('tr').children('td.secretLink').children(":first").attr("href");
window.location = url;
});
</script>
}
This worked in Chrome and in IE edge when I clicked Enter once, for both browsers
https://dotnetfiddle.net/DUvLqb
Controller/ViewModel
namespace Testy20161006.Controllers
{
public class MyItem
{
public string Name { get; set; }
public string Type { get; set; }
public string Status { get; set; }
}
public class HomeController : Controller
{
public ActionResult SearchForm()
{
return View();
}
public ActionResult SearchMe(string term)
{
return View();
}
public ActionResult Search()
{
var myItem1 = new MyItem { Name = "Name1", Status = "Stat1", Type = "Type1" };
var myItem2 = new MyItem { Name = "Name2", Status = "Stat2", Type = "Type2" };
var myItem3 = new MyItem { Name = "Name3", Status = "Stat3", Type = "Type3" };
IList<MyItem> list = new List<MyItem>();
list.Add(myItem1);
list.Add(myItem2);
list.Add(myItem3);
return View(list);
}
Search.cshtml
#model List<Testy20161006.Controllers.MyItem>
#{
ViewBag.Title = "Search";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Search</h2>
<div id="search-form">
#*changing this action*#
#*#Html.Action("SearchForm", "Item")*#
#Html.ActionLink("Click to Search", "SearchForm")
</div>
<br />
<br />
<div id="search-results">
</div>
#Html.Partial("~/Views/Home/_SearchFormPartial.cshtml")
#Html.Partial("~/Views/Home/_SearchResultsPartial.cshtml", Model)
#section scripts {
<script type="text/javascript">
$('#search-results').bind("DOMSubtreeModified", function () {
$('#items').DataTable();
});
</script>
}
_SearchFormPartial.cshtml
#*Changing Ajax.BeginForm Signature*#
#*#using (Ajax.BeginForm("Search", "Item", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "search-results"
}))
{*#
#using (Ajax.BeginForm("SearchMe", "Home", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "search-results"
}))
{
<div class="row">
<div class="col-md-3">
<input type="text" id="term" name="term" placeholder="Search by Item Name" class="form-control" autofocus />
</div>
<div class="col-md-2">
<input type="submit" value="Search" id="btnSearch" class="btn btn-default" />
</div>
</div>
}
_SearchResultsPartial
#model List<Testy20161006.Controllers.MyItem>
#{
ViewBag.Title = "Search Results";
}
<table class="table table-striped" id="items">
<thead>
<tr>
<td><strong>Name</strong></td>
<td><strong>Type</strong></td>
<td><strong>Status</strong></td>
</tr>
</thead>
#foreach (var item in Model)
{
<tr class="clickable-row">
<td>#item.Name</td>
<td>#item.Type</td>
<td>#item.Status</td>
</tr>
}
</table>
#section scripts {
<script type="text/javascript">
$(document).ready(function () {
$("#items tr").css('cursor', 'pointer');
});
$("#items tr.clickable-row").on('click', function (e, row, $element) {
var url = $(this).closest('tr').children('td.secretLink').children(":first").attr("href");
window.location = url;
});
</script>
}
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
I want to create a login screen in which,on the click of button the ajax verify the password and then then submit the form.but when i click submit button the form is submitted before the ajax call
in short the action method and ajax both call on the same button click,but i want to call ajax before action method
View
#using (Html.BeginForm("Login", "AccountAP", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="login-box">
<div class="login-logo">
<!-- /.login-logo -->
<div class="login-box-body">
<center><img src="img/ra_logo.png" class="img-responsive" width="128" height="128" /></center>
<br />
<p class="login-box-msg" style="font-size:20px !important;">Sign in to start your session</p>
<div class="form-group has-feedback">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control", #placeholder = "Email" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
<div class="form-group has-feedback">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control", #placeholder = "Password" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
<div class="row">
<!-- /.col -->
<div class="col-xs-12">
<input type="submit" class="btn btn-primary pull-right btn-block btn-flat" value="Sign In" id="btnSave"/>
</div>
<!-- /.col -->
</div>
</div>
<!-- /.login-box-body -->
</div>
</div>
}
<script type="text/javascript">
$('#btnSave').click(function (e) {
e.preventDefault();
e.alert("what's up");
});
</script>
I will suggest to capture the submit event on the form, instead of the click event on the submit button. Because people can not only submit your form by clicking the submit button, but also hitting the enter key in a textarea...etc
You will need to stop the default browser behavior of the submit event you capture so that whenever a for is submitted, browser won't post your form. In jQuery, you can stop default by doing event.preventDefault();
Check below code for that :
First Method :
#using (Html.BeginForm("Login", "AccountAP", FormMethod.Post,new { id= "submitForm" }))
{
<div class="col-xs-12">
<input type="submit" class="btn btn-primary pull-right btn-block btn-flat" value="Sign In" id="btnSave"/>
</div>
}
<script>
$(function () {
$("#btnSave").click(function(){
//Code for ajax verify the password then call below submitForm after validation
$("#submitForm").submit();
});
});
</script>
Second Method :
#using (Html.BeginForm("Login","AccountAP",FormMethod.Post, new { onsubmit = "myJsFunction()" }))
Your jquery code should be :
<script>
$(function () {
$("#btnSave").submit(function (event) {
event.preventDefault();
e.alert("what's up");
//Code for ajax verify the password then call below myJsFunction after validation
myJsFunction();
});
});
</script>
I have a view which calls a partial view via ajax. The partial view has a table which is contained in another ajax form. Each row contains two submit buttons that I wish to map to two different actions, Save and Delete. However, when I submit either button, no data gets passed to the controller. The String submitAction and ProjectComment projectcomment contains no data comment data from the form. I have the following code:
MyView:
Index.cshtml
#model MyProject.Areas.MyComments.Models.ProjectComment
#using (Ajax.BeginForm("Details", null,
new AjaxOptions
{
HttpMethod = "POST", // HttpPost
InsertionMode = InsertionMode.Replace, // empty the target first
UpdateTargetId = "commentTbl" // place content within #commentTbl
}, new { #class = "form-inline" }))
{
#Html.AntiForgeryToken()
<p>...</p>
<div class="ibox float-e-margins">...</div>
}
<div id="commentTbl">...Partial View is loaded here...</div>
Partial View
Details.cshtml
#model IEnumerable<MyProject.Areas.MyComments.Models.ProjectComment>
#using (Ajax.BeginForm("Update", null,
new AjaxOptions
{
HttpMethod = "POST", // HttpPost
InsertionMode = InsertionMode.Replace, // empty the target first
UpdateTargetId = "commentTbl" // place content within #commentTbl
}, new { #class = "form-inline" }))
{
<div class="ibox float-e-margins">
<div class="ibox-title">...</div>
<div class="ibox-content">
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover dataTables-example" id="dataTables-comments">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Comment)
</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#{int i = 0;}
#foreach (var projectcomment in Model)
{
<tr>
<td>
#Html.EditorFor(modelItem => projectcomment.Comment)
</td>
<td>
<button type="submit" id="save" class="btn btn-primary" name="Save" value='#i'>Save</button>
<button type="submit" id="delete" class="btn btn-primary" name="Delete" value='#i'>Delete</button>
</td>
</tr>
i++;
}
</tbody>
</table>
</div>
</div>
</div>
}
My Controller
CommentController.cs
[HttpPost]
public ActionResult Update(ProjectComment projectcomment, String submitAction)
{
// submitAction is null and projectcomment contains no form data.
if (submitAction.Equals("Save"))
return RedirectToAction("Save", projectcomment);
else if (submitAction.Equals("Delete"))
return RedirectToAction("Delete", projectcomment);
else
return HttpNotFound();
}
[HttpPost]
public ActionResult Save([Bind(Include="Comment")] ProjectComment projectcomment)
{
// ... to do logic here
}
Please help with what I am doing wrong.
Modify you button name to match your parameter name. For example:
Your Code:
<button type="submit" id="save" class="btn btn-primary" name="Save" value='#i'>Save</button>
<button type="submit" id="delete" class="btn btn-primary" name="Delete" value='#i'>Delete</button>
What it should be:
<button type="submit" id="save" class="btn btn-primary" name="submitAction" value='Save'>Save</button>
<button type="submit" id="delete" class="btn btn-primary" name="submitAction" value='Delete'>Delete</button>
I modified the name to match your parameter name and value you are accepting in your controller. When you submit the form, you will now be passing the value to your parameter.
I'm trying to display a dialog before sending the ajax request, but I'm not getting the correct response depending of the clicked button. but I only get two results or the dialog is displayed but the request is sent or it never sends a request.
I don't want to use pure jQuery due to my strong typed view and my controller action which expects a model, so I think this will be another very big problem I'll need to resolve.
this is my layout
<!DOCTYPE html>
<html lang="es-ES">
<head>
<title>Checador</title>
<link rel="stylesheet" href="#Url.Content("~/Content/Estilos.css")">
<meta charset="utf-8">
#RenderSection("cs", required: false)
</head>
<body>
<div class="linea"> </div>
<table border="0" align="center" cellpadding="0" cellspacing="0" id="principal">
<tr>
<td id="Cuadro" align="left" valign="middle">
<span class="slogan">SOME TITLE</span><br />
<span class="subslogan">BLAH BLAH</span>
</td>
<td id="seccion" valign="top" align="right">
<div class="lineainfo">
#using ( Html.BeginForm("LogOff", "Login", FormMethod.Post, new { id = "logoutForm" }) )
{
#Html.AntiForgeryToken()
Cerrar Sesion
}
</div>
</td>
</tr>
<tr>
<td colspan="2" valign="top" id="Central">
<div>
#RenderBody()
</div>
</td>
</tr>
<tr>
<td align="right" id="Pie_Pagina" colspan="100%"><span>Abarrotes Monterrey © 2014 Mexico(Es)</span></td>
</tr>
</table>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
#RenderSection("scripts", required: false)
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script>
function desaparece(data, textStatus, jqXHR) {
$("#MensajeRegistro").css({ "background-color": "rgb(252, 210, 7)", "visibility": "visible", "font-size": "1.5em", "color": "#121e2d !important" });
$(".MarcoResultados").hide("slow", function () {
});
setTimeout(function () {
$("#MensajeRegistro").css("visibility", "hidden");
}, 1550);
}
$(".number").keyup(function (event) {
var valor = $(this).val();
//var valor2 = valor.charAt(0);
$(this).val(valor);
});
$(".number").keypress(function (event) {
var valor = $(this).val();
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
});
</script>
</body>
</html>
below is my partial view
#model checa.Models.WrapperCla
#{
ViewBag.Title = "ChecarEntradas";
}
#section cs{
<style>
#dialog-confirm {
display:none;
}
</style>
}
<div id="MensajeRegistro">
#{Html.RenderPartial("~/Views/Checador/_MensajeRegistro.cshtml",Model);}
</div>
#using ( Ajax.BeginForm("Buscar", Model.singlemp, new AjaxOptions { UpdateTargetId = "BusquedaEmpleados", HttpMethod = "Post" }) )
{
#Html.Label("Nombres")<input type="text" id="Nombres" name="Nombres" />
#Html.Label("Apellidos")<input type="text" id="Apellidos" name="Apellidos" />
#Html.Label("Clave")<input type="text" id="idd" name="idd" class="number" />
#Html.Label("Departamento")<input type="text" id="Departamento" name="Departamento" />
<input type="submit" value="Buscar" />
}
<div id="dialog-confirm" title="Empty the recycle bin?">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>
<div id="BusquedaEmpleados" class="ResultadosEmpleados">
#{Html.RenderPartial("~/Views/Checador/_EmpleadosEncontrados.cshtml",Model.Empleados);}
</div>
#section Scripts
{
<script type="text/javascript">
function Confirmacion() {
var response = false;
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
"Cofirmar": function () {
noenvio(response);
$(this).dialog("close");
},
"Cancelar": function () {
response = false;
$(this).dialog("close");
}
}
});
return response;
}
function noenvio(response) {
response = false;
return response;
}
</script>
}
this one is another partial view which displays the query results of the partial view
#model checa.Models.WrapperCla
<div class="MarcoResultados">
#foreach ( var epm in Model.Empleadoslist )
{
using ( #Ajax.BeginForm("Checar", epm, new AjaxOptions { UpdateTargetId = "MensajeRegistro", HttpMethod = "Post", OnSuccess = "desaparece(data, status, xhr)", OnBegin = "return Confirmacion()" },
new { Class = "empleadoForm" }) )
{
<div class="empleado">
#{
String convertido = "";
if ( epm.Foto != null )
{
convertido = System.Convert.ToBase64String(epm.Foto);
}
<img class="fempleado" src="data:image;base64,#convertido" width="80" height="80" />
}
<label>Empleado:#epm.nombres #epm.apellidos</label>
<label>Numero Empleado:#epm.idd</label>
<label>Departamento:#epm.Departamento</label>
<input type="submit" value="Checar" />
</div>
}
}
</div>