<img> element with onclick submits the form instead of firing action - asp.net-mvc

I am having a weird issue in my Login.cshmtl view which I posted below. So on the top right corner of my login page, I have two textboxes for credentials and two .png images as their labels, a "Remember Me" checkbox and a .png image as its label, and finally a "ForgotPassword" .png image defined as:
<img onclick="location.href ='#Url.Action("ForgotPassword", "Account")'" src="~/Content/Images/ForgotPassword.png" />
Everything worked fine until I changed this line as follows:
<input type="image" onclick="location.href ='#Url.Action("ForgotPassword", "Account")'" src="~/Content/Images/ForgotPassword.png" />
Surprisingly, now my image-button is broken and it submits the page! Using the debugger I observe that POST method of my Login action is called instead of ForgotPassword action. Can you please explain how this happens? Below, I am posting the Login.cshtml view with irrelevant parts removed.
#model FooProject.Web.ViewModels.LoginViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
....
</head>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="navbar navbar-fixed-top">
<div class="navbar-header">
<input type="image" class="navbar-brand" onclick="location.href ='#Url.Action("Index", "Home")'" src="~/Content/Images/logo.png"/>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav" style="margin:10px">
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
<div class="nav navbar-nav navbar-right">
<div class="row">
<div class="col-md-5">
<span class="actionLink">
<img src="~/Content/Images/Username.png"/>
</span>
</div>
<div class="col-md-7">
<span class="actionLink">
<img src="~/Content/Images/Password.png"/>
</span>
</div>
</div>
#using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "loginForm", #class = "navbar-right form-inline" }))
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-5">
#Html.TextBoxFor(m => m.UserName, new { #class = "" })
</div>
<div class="col-md-5">
#Html.PasswordFor(m => m.Password) <br />
</div>
<div class="col-md-2" style="padding-left:0">
<input type="image" alt="Submit" src="~/Content/Images/Login.png" style="width:45px" />
</div>
</div>
<div class="row">
<div class="col-md-5">
#Html.CheckBoxFor(m => m.RememberMe)
<span class="actionLink">
<img src="~/Content/Images/RememberMe.png" style="height:11px;vertical-align:top;margin-top:2px" />
</span>
</div>
<div class="col-md-7">
<img onclick="location.href ='#Url.Action("ForgotPassword", "Account")'" src="~/Content/Images/ForgotPassword.png" />
</div>
</div>
}
</div>
</div>
</div>
</div>
</div>
</body>
</html>

<input type="image"> works as submit button, so this is expected behavior.
But there is solution:
<input type="image" onclick="location.href ='#Url.Action("ForgotPassword", "Account")'; return false;" src="~/Content/Images/ForgotPassword.png" /> will do the trick.
By adding return false; you prevent submission from being executed.
There is also alternative solution:
There is no reason to replace img tag with input. If you want to see cursor on hover, you can do it with CSS:
img.submit:hover {
cursor: pointer;
}
and decorate img with submit class:
<img class="submit" onclick="location.href ='#Url.Action("ForgotPassword", "Account")'" src="~/Content/Images/ForgotPassword.png" />
And the way I would do that:
<a href='#Url.Action("ForgotPassword", "Account")'>
<img src="/Content/Images/ForgotPassword.png" />
</a>

By changing the image tag to an input tag you've create an image as a submit button and it's doing what you should expect: submitting the form with the action and method defined.
See http://www.w3schools.com/tags/att_input_type.asp for more information

From the W3C Wiki (emphasis is mine):
The image button state represents either an image from which a user
can select a coordinate and submit the form, or alternatively a button
from which the user can submit the form. The element is a button,
specifically a submit button

Related

Kendo Editor not showing toolbar in Razor page using MVC 5

I am trying to use the Kendo Editor in a simple Razor page. I put in the code from the Telerik site for both initializing the Editor and for the Basic Configuration as seen on the
https://docs.telerik.com/aspnet-mvc/html-helpers/editors/editor/overview page. In neither case does the Toolbar display no matter if I click inside the editable area or not. For example, this is the page containing the Basic Configuration:
#using Kendo.Mvc.UI
#model TYX.Entities.Banner
#{
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Create Alert Banner</title>
</head>
<body>
#*#Html.AntiForgeryToken()*#
#(Html.Kendo().Editor()
.Name("editor")
.HtmlAttributes(new { style = "width: 100%;height:440px" })
.Value(#<text>
<p>
Kendo UI Editor allows your users to edit HTML in a familiar, user-friendly way.
</p>
</text>)
)
<script type="text/javascript">
$(function () {
// The Name() of the Editor is used to get its client-side instance.
var editor = $("#editor").data("kendoEditor");
});
</script>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>
The output page contains the Editor text edit area, but nothing I do makes the Toolbar show.
I have another Razor page from a different project that displays the toolbar without any problem and it is displayed as soon as the page loads. Here is the page code for that instance:
<div class="card-body card-padding p-t-0">
<div class="row">
<div class="col-md-6">
<form id="bannerForm">
#Html.HiddenFor(x => x.Id)
<div class="form-group row align-items-center">
<label class="col-xl-2 col-form-label">Banner Body</label>
<div class="col-xl">
<div id="banner-body" class="k-content editor">
#(Html.Kendo().EditorFor(m => m.Body)
.Name("Body")
.HtmlAttributes(new { style = "width: 100%; height:420px", aria_label = "Body" })
.Tools(tools => tools
.Clear()
.Formatting()
.Bold().Italic().Underline()
.CleanFormatting()
.JustifyLeft().JustifyCenter().JustifyRight()
.InsertUnorderedList().InsertOrderedList()
.Outdent().Indent()
.CreateLink().Unlink()
.ViewHtml()
.TableEditing()
)
)
</div>
</div>
</div>
<div class="form-group row">
<label class="col-xl-2 col-form-label">Is Active</label>
<div class="col-xl">
#Html.CheckBoxFor(m => m.IsActive)
</div>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-md-12">
</div>
</div>
<div class="row">
<div class="col-md-12">
<hr />
</div>
</div>
<div class="col d-flex justify-content-end">
<button class="btn btn-primary px-3"
type="button"
onclick="saveBanner();">
Save
</button>
</div>
</div>
Here is a screenshot of the output:
Any idea why my toolbar is not showing? Also, I pasted the code from the working page into my page and it doesn't show the toolbar either.

How to fix the layout issue of chosen-select styles in bootstrap?

I am trying to apply a style by using bootstrap css but every time i am being un-successful .
What i am trying to do is :
<link href="~/Theme/css/chosen.css" rel="stylesheet" />
<link href="~/Theme/Bootstrap37/css/chosen-bootstrap.css" rel="stylesheet" />
<section id="contact-page" class="EditMode" style="display:none;">
<div class="container">
<div class="row ">
<div class="status alert alert-success" style="display: none"></div>
<div class="col-md-12 col-xs-12">
<h5> Change your information</h5>
<form id="" class="" name="c_signup" method="post" action='#Url.Action("CSignUp","Profile", new { area="CPortal"})'
enctype="multipart/form-data" onSubmit="return validation(this)">
<div class="col-xs-6">
<div class="form-group">
<label>Speciality</label>
<div >
#Html.HiddenFor(m => m.SelectedSpecialityTest)
#Html.ListBoxFor(m => m.SelectedSpecialityIds,
new MultiSelectList(Model.Specialities, "OID", "SpecialityDesc"),
new { #class = "chosen-select form-control", #required = "required" })
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
jQuery(document).ready(function () {
$(".chosen-select").chosen({ no_results_text: "Oops, nothing found!" });
});
Now when i see the view then chosen-select dropdown is not displaying instead just a tiny line.
See the complete working same at here:
https://codepen.io/maifs/pen/VWMwWw

Unobtrusive ajax - View being fully replaced by partial view

I have searched multiple examples and have tried several things to get this to work properly. Currently I am trying to get a div to be replaced by using an Ajax.HtmlLink pointing to a PartialViewResult method.
I have tried
Checking network and javascript consoles to make sure my .js are all being loaded
Unbundling the stock jqueryval bundle and including the scripts manually
Double checked I didn't have another DOM element with the same update target Id
Checked my ajaxoptions to ensure everything was correct
I know unobtrusive is working because my Email duplicate remote validation check is working.
I will now show some screen shots of my debugging process
Here is what the page looks like prior to ajax load
My goal is to replace the container on the right that is currently holding email, name, and zipcode values
Here is the result##
This is what my view code looks like
<div class="container">
<br />
<br />
<div class="row">
<div class="col-sm-3">
<div class="sidebar-account">
<div class="row ">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">My Account</div>
<div class="panel-body">
<ul class="nav">
<li>
<a class="active" href="account_dashboard.html">Me</a>
</li>
<li>
#Ajax.ActionLink("Alerts", "ManageAlerts", null, new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "ajax-update",
InsertionMode = InsertionMode.Replace,
OnBegin = "ajaxBegin",
OnFailure = "ajaxFail",
OnComplete = "ajaxComplete",
OnSuccess = "ajaxSuccess"
}, new { #class = "active" })
</li>
<li>
<a class="active" href="account_account.html">Linked Accounts</a>
</li>
<li>
<a class="active" href="account_ads.html">Manage ads</a>
</li>
<li>
<a class="active" href="account_ad_create.html">Create new ad</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="row hidden-xs">
<div class="col-lg-12">
<div class="well">
<div class="row ">
<div class="col-lg-3">
<img src="css/images/icons/Crest.png" width="45" />
</div>
<div class="col-lg-9">
<h4 style="margin-top: 0">Increase visibility</h4>
<p>Don't forget to 'bump' your listing to gain more visibility</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-9">
<div id="ajax-update">
#Html.Partial("_ManageUserAccount", Model)
</div>
</div>
<br />
</div>
Partial View Code##
<div id="fadein-div">
<div class="panel panel-default">
<div class="panel-heading">#Model.Username : Alerts</div>
<div class="panel-body">
<br />
<div class="row">
<div class="col-sm-12">
<p><span style="font-weight:bold">Change your alerts!</span></p>
</div>
</div>
<br />
#using (Html.BeginForm("ManageAlerts", "Account", FormMethod.Post, new { #class = "form-vertical", role = "form" }))
{
#Html.AntiForgeryToken()
<fieldset>
<div class="row">
<div class="col-sm-12 ">
<div class="form-group">
<div class="row">
<div class="col-sm-2">
<div class="checkbox">
#Html.CheckBoxFor(P => P.EmailAlertsOn) #Html.LabelFor(P => P.EmailAlertsOn)
</div>
</div>
</div>
</div>
<div id="control-div">
<div class="form-group">
<h3>Email alert options</h3>
</div>
<div class="form-group">
<div class="checkbox">
#Html.CheckBoxFor(P => P.EmailOnNewMessageOn) #Html.LabelFor(P => P.EmailOnNewMessageOn)
</div>
<div class="text-danger">
#Html.ValidationMessageFor(P => P.EmailOnNewMessageOn)
</div>
</div>
<div class="form-group">
<div class="checkbox">
#Html.CheckBoxFor(P => P.EmailOnReplyOn) #Html.LabelFor(P => P.EmailOnReplyOn)
</div>
<div class="text-danger">
#Html.ValidationMessageFor(P => P.EmailOnReplyOn)
</div>
</div>
<div class="form-group">
<div class="checkbox">
#Html.CheckBoxFor(P => P.EmailOnAccountUpdateOn) #Html.LabelFor(P => P.EmailOnAccountUpdateOn)
</div>
<div class="text-danger">
#Html.ValidationMessageFor(P => P.EmailOnAccountUpdateOn)
</div>
</div>
</div>
<br />
<button type="submit" class="btn btn-primary">Save details</button>
</div>
</div>
</fieldset>
}
</div>
</div>
And finally, controller code##
[HttpGet]
public PartialViewResult ManageAlerts()
{
var user = UserManager.FindById(Guid.Parse(User.Identity.GetUserId()));
Models.Account.ManageAlertsViewModel vm = new ManageAlertsViewModel();
vm.Username = user.UserName;
vm.EmailAlertsOn = user.EmailAlertsOn;
vm.EmailOnAccountUpdateOn = user.EmailOnAccountUpdateOn;
vm.EmailOnNewMessageOn = user.EmailOnNewMessageOn;
vm.EmailOnReplyOn = user.EmailOnReplyOn;
return PartialView("_ManageAlerts", vm);
}
<!-- js library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
<script src="~/Themes/Authenticity%20Forms/Authenty/js/bootstrap.min.js"></script>
<script src="~/Themes/Authenticity%20Forms/Authenty/js/jquery.icheck.min.js"></script>
<script src="~/Themes/Authenticity%20Forms/Authenty/js/waypoints.min.js"></script>
<!-- authenty js -->
<script src="~/Themes/Authenticity%20Forms/Authenty/js/authenty.js"></script>
<!-- preview scripts -->
<script src="~/Themes/Authenticity%20Forms/Authenty/js/preview/jquery.malihu.PageScroll2id.js"></script>
<script src="~/Themes/Authenticity%20Forms/Authenty/js/preview/jquery.address-1.6.min.js"></script>
<script src="~/Themes/Authenticity%20Forms/Authenty/js/preview/scrollTo.min.js"></script>
<script src="~/Themes/Authenticity%20Forms/Authenty/js/preview/init.js"></script>
#Scripts.Render("~/bundles/jqueryval")

File Upload using recent Bootstrap file upload and mvc asp.net

I looked over some other answers and the solutions there were not working. And I couldn't seem to figure out why. This is using Bootstrap 3.0. All I am trying to do is use that to upload a new avatar image. The problem is it always comes up null and I cannot seem to figure out why.
Here is my HTML:
#using (Html.BeginForm("EditAvatar", "Profile", new { userID = #Model.ProPit_User.userID }, FormMethod.Post, new { }))
{
<div class="form-group">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail" style="width: 200px; height: 150px;">
<img src="http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image" alt="" />
</div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;">
</div>
<div>
<span class="btn default btn-file">
<span class="fileinput-new">Select image
</span>
<span class="fileinput-exists">Change
</span>
<input id="avatar_image" type="file" name="..." runat="server">
</span>
<a href="#" class="btn default fileinput-exists" data-dismiss="fileinput">Remove
</a>
</div>
</div>
<div class="clearfix margin-top-10">
<span class="label label-danger">NOTE!
</span>
<span>Attached image thumbnail is supported in Latest Firefox, Chrome, Opera, Safari and Internet Explorer 10 only
</span>
</div>
</div>
<div class="margin-top-10">
<button type="submit" class="btn green">
Save Changes
</button>
<button type="reset" class="btn default">Cancel</button>
</div>
}
I have given the file input the ID of avatar_image
Here is the controller:
[HttpPost]
public ActionResult EditAvatar(HtmlInputFile avatar_image)
{
if (avatar_image.PostedFile != null)
{
//do whatever you want with the file
}
return View();
}
When looking at the break point the avatar_image.PostedFile is always null. Anyone have any idea what I am missing?
You might check the request in Fiddler. More importantly though, you need to add the enctype="multipart/form-data" attribute to the form.

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/SiteLayout.cshtml": "Scripts"

I have a simple view:
#model BootstrapTest4.Models.Account.CambioDeClave
#{
Layout = "~/Views/Shared/SiteLayout.cshtml";
}
<h2>#Model.Title</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<div class="editor-label">
#Html.LabelFor(model => model.Pass1)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Pass1)
#Html.ValidationMessageFor(model => model.Pass1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Pass2)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Pass2)
#Html.ValidationMessageFor(model => model.Pass2)
</div>
<p>
<input type="submit" value="Cambiar Clave" />
</p>
</fieldset>
}
#section Scripts {
#System.Web.Optimization.Scripts.Render("~/bundles/jqueryval")
}
this view was made via the Mvc4 scaffolding system (edit template) and since I use some dataannotations in my model it uses the Scripts Bundle.
the error I am getting is the following:
The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/SiteLayout.cshtml": "Scripts"
searching I found that most people solve the problem adding this to their layout:
#if (IsSectionDefined("Scripts"))
{
RenderSection("Scripts",false);
}
I added that block just before the tag of my layout but i still get the same error.
as requested: my whole Layout:
#model BootstrapTest4.Models.IMenu
#using BootstrapTest4.Utils.Helpers
#using BootstrapTest4.Utils
#{
Layout = null;
}
<!DOCTYPE html>
#{
Model.usr = (UsuarioWebCliente)Session["DatosUsr"];
Model.usrDrogSelec = Html.DrogSeleccionada(Model.usr);
var Lista = Html.GeneraComboDrogs2(Model.usr, Model.usrDrogSelec.cod_drogueria);
}
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>#ViewBag.Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="~/Scripts/jquery-1.9.1.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
<!-- Bootstrap -->
<link href="~/Content/bootstrap/bootstrap.css" rel="stylesheet" media="screen">
</head>
<body style="height: 100%; ">
<div class="wrapper">
<div>
<div id="whitebar">
<div class="container">
<div class="row">
<div class="col-md-6">
</div>
<div class="col-md-6" style="text-align: right">
#Model.usr.DatUsrs.desc_usuario - #Model.usr.DatUsrs.codigo_ident - #Html.ActionLink("Cerrar Sesion","Logout","Account")
</div>
</div>
</div>
</div>
<div id="bluebar">
<div class="container">
<div class="row">
<div class="col-md-4">
#Html.DropDownListFor(x => x.usr.DatUsrs.cod_drogueria, new SelectList(Lista, "Value", "Text"), new { #id = "DDLMENU", data_url = Url.Action("CambiarDrog", "Menu") })
</div>
<div class="col-md-3">
Monto Consumido:
<label id="SALDO">
#(Model.usrDrogSelec.saldo_actual == 0 ? "0.00" : Convert.ToDecimal(Model.usrDrogSelec.saldo_actual).ToString("#,##.00"))
</label>
</div>
<div class="col-md-3">
Hora Corte: XXXXX
</div>
<div class="col-md-2">
Día Corte:
<label id="DIA">
#Model.usrDrogSelec.dia_corte
</label>
</div>
</div>
</div>
</div>
<nav class="navbar navbar-default" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">
<img style="max-height: 20px;" src="~/Content/Images/1381797224_home.png" />
</a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
#foreach (var item in Model.MenuCollection)
{
<li class="dropdown">
#item.Name <b class="caret"></b>
#if (item.Children.Count > 0)
{
<ul class="dropdown-menu">
#foreach (var childItem in item.Children)
{
<li>#Html.ActionLink(childItem.Name, childItem.Action, childItem.Controller)</li>
}
</ul>
}
</li>
}
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<span class="glyphicon glyphicon-cog"></span><b class="caret"></b>
<ul class="dropdown-menu">
<li>#Html.ActionLink("Droguería Principal","PrioridadDrogueria","ReportesPrioridadDrogueria")</li>
<li>Mensajería </li>
<li> #Html.ActionLink("Cambio de Clave", "CambiarClave", "Account")</li>
<li>Actualizar Datos</li>
</ul>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</nav>
<div id="Content" style="height: 100%; ">
#RenderBody()
</div>
</div>
<div class="push"></div>
</div>
<div class="footer">
<div class="row">
<div class="col-md-12 footer">Test</div>
</div>
</div>
#if (IsSectionDefined("Scripts"))
{
RenderSection("Scripts",false);
}
</body>
</html>
Did you try only
RenderSection("Scripts",false);
Instead of
#if (IsSectionDefined("Scripts"))
{
RenderSection("Scripts",false);
}
You should just call RenderSection.
#RenderSection("Scripts", false)
I got the following error while running the application I resolved it by adding #RenderSection(“Scripts”,required:false) in the _Layout page.
#RenderSection("scripts", required: false)

Resources