I'm using this jQuery from CodePen https://codepen.io/dicson/pen/eJzoEX & it's working great however it is somehow blocking the FormMethod.Post action from firing. I'm not very experienced with JS / JQuery so hoping someone can help.
FORM
#using (Html.BeginForm("Login", "Authentication", FormMethod.Post, new { role = "form" }))
{
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<form class="form">
<div class="f_row">
<label>Username</label>
#Html.TextBoxFor(m => m.Email, new { #name = "username", #type = "username", #class = "input-field", #required = "" })
#Html.ValidationMessageFor(m => m.Email, "", new { #class = "text-danger" })
<u></u>
</div>
<div class="f_row last">
<label>Password</label>
#Html.PasswordFor(m => m.Password, new { #name = "pass", #type = "password", #class = "input-field", #required = "" })
#Html.ValidationMessageFor(m => m.Password, "", new { #class = "text-danger" })
<u></u>
</div>
<div class="form-group">
<input type="submit" value="GO" class="btn btn-default submit-btn input-field" />
</div>
</form>
}
JQUERY
var inP = $('.input-field');
inP.on('blur', function () {
if (!this.value) {
$(this).parent('.f_row').removeClass('focus');
} else {
$(this).parent('.f_row').addClass('focus');
}
}).on('focus', function () {
$(this).parent('.f_row').addClass('focus');
$('.btn').removeClass('active');
$('.f_row').removeClass('shake');
});
$('.resetTag').click(function(e){
e.preventDefault();
$('.formBox').addClass('level-forget').removeClass('level-reg');
});
$('.back').click(function(e){
e.preventDefault();
$('.formBox').removeClass('level-forget').addClass('level-login');
});
$('.regTag').click(function(e){
e.preventDefault();
$('.formBox').removeClass('level-reg-revers');
$('.formBox').toggleClass('level-login').toggleClass('level-reg');
if(!$('.formBox').hasClass('level-reg')) {
$('.formBox').addClass('level-reg-revers');
}
});
$('.btn').each(function() {
$(this).on('click', function (e) {
e.preventDefault();
var finp = $(this).parent('form').find('input');
console.log(finp.html());
if (!finp.val() == 0) {
$(this).addClass('active');
}
setTimeout(function () {
inP.val('');
$('.f_row').removeClass('shake focus');
$('.btn').removeClass('active');
}, 2000);
if (inP.val() == 0) {
inP.parent('.f_row').addClass('shake');
}
//inP.val('');
//$('.f_row').removeClass('focus');
});
});
If I dont load the jquery the form works fine.
I get an undefined log on the console when running the jquery
Related
I have a radio button which has option to show or hide div content defending of radiobutton state, but after i fill the form and I press F5 the previous state stay, but div class is dissapear.
$(document).ready(function () {
$("input[name$='Chapel']").click(function () {
var test = $(this).val();
if (test == 'No') {
$("div#hideChapel").hide();
}
else {
$("div#hideChapel").show();
}
});
});
HTML
<div class="form-group">
#Html.LabelFor(model => model.Chapel, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
<label class="radio-inline">
#Html.RadioButtonFor(model => model.Chapel, "Yes", new { #class = "styled", htmlAttributes = new { #checked = "true", #name = "Chapel"} }) Yes
</label>
<label class="radio-inline">
#Html.RadioButtonFor(model => model.Chapel, "No", new { #class = "styled", htmlAttributes = new { #checked = "true" , #name = "Chapel" } })
No
</label>
#Html.ValidationMessageFor(model => model.Chapel, "", new { #class = "text-danger" })
</div>
</div>
Any comment, where It should be problem ?
After page refresh if you want to show a div then you need to add that code outside click function.
$(document).ready(function () {
// Add logic when to show this div
$("div#hideChapel").show(); // Here you go
$("input[name$='Chapel']").click(function () {
var test = $(this).val();
if (test == 'No') {
$("div#hideChapel").hide();
}
else {
$("div#hideChapel").show();
}
});
});
I am trying to Post a Partial View's data to the server to save the input fields result to database and then return back to the same (partial view which is open as a modal dialog) or return to the parent view which called the modal dialog.
But for some reason, I am not getting the Action method's parameter (i.e. weldMaster) in the Controller which is being sent from the ajax method call.
Here is my controller method.
// GET: WeldMasters/Details/5
public ActionResult Details(int? ids, bool isPartials = false)
{
if (ids == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
WeldMaster weldMaster = db.WeldMasters.Find(ids);
ViewBag.Readonly = false;
if (weldMaster == null)
{
return HttpNotFound();
}
if(isPartials)
return PartialView(weldMaster);
else
return View(weldMaster);
}
// POST: WeldMasters/Details/5
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Details**(WeldMaster weldMaster)**
//{"The parameter conversion from type 'System.String' to type 'IMCC_PAS.Entities.WeldMaster' failed because no type converter can convert between these types."}
{
var success = 0;
if (ModelState.IsValid)
{
success = 1;
db.Entry(weldMaster).State = EntityState.Modified;
db.SaveChanges();
return Json(new { success });
}
return Json(new { success });
}
Here is the ajax code
<script type="text/javascript">
$(document).ready(function () {
$(".saveBtn").click(function (e) {
debugger;
var token = $('input[name="__RequestVerificationToken"]').val();
// If I dont pass the token in the `data` parameter of ajax, then action method of controller is not called at all.
e.preventDefault();
$.ajax({
type: "POST",
url: '#Url.Action("Details", "WeldMasters")',
data: { __RequestVerificationToken: token, weldMaster: $('#__AjaxAntiForgeryForm').serialize() },
success: function (result) {
alert(result);
},
failure: function (response) {
alert(result.responseText);
},
error: function (response) {
alert(result.responseText);
}
});
});
});
</script>
Here is the modal for the partial view
#model IMCC_PAS.Entities.WeldMaster
and here is the form
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.id)
<div class="row">
<div class="col-md-3 col-sm-12">
#Html.LabelFor(model => model.weld_no, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-3 col-sm-12">
#Html.LabelFor(model => model.rep_no, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-3 col-sm-12">
#Html.LabelFor(model => model.length, htmlAttributes: new { #class = "control-label" })
</div>
<div class="col-md-3 col-sm-12">
#Html.LabelFor(model => model.normal_size, htmlAttributes: new { #class = "control-label" })
</div>
</div>
<div class="row">
<div class="col-md-3 col-sm-12">
#Html.EditorFor(model => model.weld_no, ViewBag.Readonly ? (object)new { htmlAttributes = new { #readonly = "readonly", #class = "form-control" } } : new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-3 col-sm-12">
#Html.EditorFor(model => model.rep_no, ViewBag.Readonly ? (object)new { htmlAttributes = new { #readonly = "readonly", #class = "form-control" } } : new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-3 col-sm-12">
#Html.EditorFor(model => model.length, ViewBag.Readonly ? (object)new { htmlAttributes = new { #readonly = "readonly", #class = "form-control" } } : new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-3 col-sm-12">
#Html.EditorFor(model => model.normal_size, ViewBag.Readonly ? (object)new { htmlAttributes = new { #readonly = "readonly", #class = "form-control" } } : new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group modal-footer">
<div class="col-md-12">
<a class="saveBtn" href="javascript:void(0);">Edit</a>
</div>
</div>
</div>
}
EDIT: Here is the parent view which has the selection parameters for showing the weld details. And then Weld details are shown in a div (for readonly purpose) and can be edited in a popup modal dialog on a button click.
<script>
$(document).ready(function () {
... more code for other dropdowns here
//When Wled No is changed, reload Weld Details in its respective Partial view
$("#weldddl").change(function () {
var parameter = { ids: $("#weldddl").val(), isPartials: true };
$.ajax({
url: '/WeldMasters/Details/',
type: 'GET',
data: parameter,
success: function (result) {
var div = $('#weldDetails');
div.html('');
div.html(result);
}
});
});
$(".editWeldBtn").click(function () {
//debugger;
$('#MyModal').empty();
$('#MyModal').append(GetModalDialog());
var link = '#Url.Action("Details", "WeldMasters")';
data = { ids: $("#weldddl").val(), isPartials: true };
LaunchModalDlg(link, data, "View Weld Master Information", "75%");
});
});
</script>
<h4>Index</h4>
<script src="~/Scripts/MyScripts.js"></script>
<p>
#Html.ActionLink("Create New", "Create") |
<a class="editWeldBtn" href="javascript:void(0);">Edit</a>
</p>
<div class="row">
<div class="col-sm-3">
#Html.LabelFor(model => model.Discipline, htmlAttributes: new { #class = "control-label col-md-12" })
<div class="col-md-12">
#Html.DropDownListFor(model => model.Discipline, (SelectList)ViewBag.disciplines, htmlAttributes: new { #class = "form-control", #id = "disciplineddl" })
#Html.ValidationMessageFor(model => model.Discipline, "", new { #class = "text-danger" })
</div>
#Html.LabelFor(model => model.DrawingNo, htmlAttributes: new { #class = "control-label col-md-12" })
<div class="col-md-12">
#Html.DropDownListFor(model => model.DrawingNo, (SelectList)ViewBag.drawings, htmlAttributes: new { #class = "form-control", #id = "drawingddl" })
#Html.ValidationMessageFor(model => model.DrawingNo, "", new { #class = "text-danger" })
</div>
#Html.LabelFor(model => model.ComponentNo, htmlAttributes: new { #class = "control-label col-md-12" })
<div class="col-md-12">
#Html.DropDownListFor(model => model.ComponentNo, (SelectList)ViewBag.components, htmlAttributes: new { #class = "form-control", #id = "componentddl" })
#Html.ValidationMessageFor(model => model.ComponentNo, "", new { #class = "text-danger" })
</div>
#Html.LabelFor(model => model.WeldNo, htmlAttributes: new { #class = "control-label col-md-12" })
<div class="col-md-12">
#Html.DropDownListFor(model => model.WeldNo, (SelectList)ViewBag.components, htmlAttributes: new { #class = "form-control", #id = "weldddl" })
#Html.ValidationMessageFor(model => model.WeldNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-9" id="weldDetails"> <!--This is for showing the partial view for showing weld details-->
</div>
<div id="MyModal"></div> <!--This is for pop up modal dialog-->
</div>
If you are serializing the full form then you don't need to send explicitly anti forgery token.
use this:
data: $('#__AjaxAntiForgeryForm').serialize(),
when i am trying to hide the validation message onclick of the textbox it is not hiding could you please help me out
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", #autocomplete = "off", onclick = "clearValidation()" })
#Html.ValidationMessageFor(m => m.Email, "", new { #style = "color:white; font-weight:normal; margin-left:-155px;" })
</div>
<script>
function clearValidation() {
document.getElementsByClassName("validation-summary-errors").style.color = "#ff0000";
}
</script>
Use this-
$.fn.clearValidation= function () {
$(this).each(function() {
$(this).find(".field-validation-error").empty();
$(this).trigger('reset.unobtrusiveValidation');
});
};
JS:
<script type="text/javascript">
$('#dialog').dialog({
autoOpen: false,
width: 600,
modal: true,
buttons: {
"Yes": function () {
$("#DSCreateForm").submit(); // part that isn't working correctly
},
"Cancel": function () { $(this).dialog("close"); }
}
});
var hobbsValue = $('#HobbsValue').val();
alert(hobbsValue);
if (hobbsValue == null || hobbsValue.length == 0) {
$('.btnSubmitDS').on("click", function (e) {
e.preventDefault();
$(function () {
$('#dialog').dialog('open')
});
});
}
</script>
CSHTML:
#using (Html.BeginForm("Create", "DailySummaries", FormMethod.Post, new { id = "DSCreateForm" }))
<div class="form-group">
#Html.LabelFor(model => model.Hobbs, "HOBBS:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Hobbs, new { htmlAttributes = new { id = "HobbsValue", #class = "form-control hobbs-textbox", #placeholder = "xxxx.x" } })
#Html.ValidationMessageFor(model => model.Hobbs, "", new { #class = "text-danger" })
</div>
</div>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "...")] DailySummary dailySummary)
{
In the above code, when the 'Yes' button is selected, it is submitting but when I debugged it isn't going to the HttpPost Method of the controller. How do I get it to do so?
I'm making the bold assumption that you haven't set
method="post"
On your form?
Edit: now you've supplied your form create code, I can see that isn't the case.
I have problem. I open my website on for example on: localhost:9999/Product/Index
When I click Create icon that displays a modal popup with page /Product/Crate
I click Save.
All the records in the database correctly, but it redirects me to page /Product/Crate, and I would like to only close my modal window.
What sholuld I do?
Model:
public partial class Prod
{
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public byte[] PFile { get; set; }
}
Index View:
#using (Html.BeginForm("Create", "Products", FormMethod.Post, new {
enctype = "multipart/form-data" })){
#Html.ActionLink(" ", "Create", "Products", null, new { data_modal = "", id = "btnCreate", #class = "btn btn-small
btn-primary pull-right fa fa-cart-plus" })
#Html.ActionLink(" ", "Create", "Products", null, new { id =
"btnCreate", #class = "btn btn-small btn-primary pull-right fa
fa-cart-plus" }) }
Create View:
#using (Html.BeginForm("Create", "Products", FormMethod.Post, new { id = "form1", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ProductName, "Name", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.EditorFor(model => model.ProductName)
#Html.ValidationMessageFor(model => model.ProductName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductDescription, "Name", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.EditorFor(model => model.ProductDescription)
#Html.ValidationMessageFor(model => model.ProductDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PFile, "File", htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.TextBoxFor(model => model.PFile, new { type = "file", name = "imageF" })
#Html.ValidationMessageFor(model => model.PFile, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Anuluj</button>
<input class="btn btn-primary" type="submit" value="Zapisz" />
</div>
}
Controller:
[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = "PFile")] Prod pro, HttpPostedFileBase imageF)
{
if (ModelState.IsValid)
{
if (imageF != null)
{
pro.PFile= new byte[imageF.ContentLength];
imageF.InputStream.Read(pro.PFile, 0, imageF.ContentLength);
}
db.Prods.Add(pro);
db.SaveChanges();
return Json(new { success = true });
}
return PartialView("Create", pro);
}
modalform.js
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
// hide dropdown if any
$(e.target).closest('.btn-group').children('.dropdown-toggle').dropdown('toggle');
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
/*backdrop: 'static',*/
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form1', dialog).submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $('#file').serialize(),
contentType: 'multipart/form-data',
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
//Refresh
location.reload();
} else {
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
}); }
Please help to solve this.