MVC onfocusout event not firing - c#

Im getting confused about the onfocusout event in my mvc view.
<div class="editor-field" id="supplieridentificationID" >
#Html.EditorFor(m => m.SupplierIdentification)
</div>
<div id="suppliername" class="editor-label" />
And my javascript code:
$('#supplieridentificationID').onfocusout(function () { alert("ajax here!" })
I cant get this to work, actually im trying to send the SupplierIdentification to my controller and get the Json with the SupplierName and put on "suppliername" label.
All using onfocusout function with the ajax.
Any sugestions?
EDIT:
I tried other code, and still not getting nothing:
<div>
<fieldset>
<legend>Novo Documento</legend>
<div class="editor-field" id="ident">
#Html.EditorFor(m => m.SupplierIdentification)
</div>
</fieldset>
</div>
And script:
<script type="text/javascript">
$(document).ready(function() {
$('#ident').focusin(function () { alert("focusin"); });
});

Use focusout instead of onfocusout
$('#SupplierIdentification').focusout(function() { alert("ajax here!" });

try adding an id to control so you can reference it in Jquery.
#Html.EditorFor(m => m.SupplierIdentification, new { #id = "id"})
$(document).ready(function() {
$('#id').blur(function () {
alert("focusin");
});
});
blur function happens when element loses focus

Related

Can't get Jquery datepicker to work in my asp.net mvc project

I have a simple page where i want to add a datepicker to my textboxfor and just modify the format but there is simply nothing showing on the page, I have tried to import all the scripts they said necessary on jquery datepicker documentation here : https://jqueryui.com/datepicker/
Here is my cshtml page on my project with what I have tried to make it work as of now:
#using System.Web.UI.WebControls
#using InscriptionCentreFormation.Controllers
#using InscriptionCentreFormation.Models
#model INSC_Inscription
#{
ViewBag.Title = "InscriptionFormation";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<br />
#using (Html.BeginForm("InscriptionFormation", "DetailProduit"))
{
#Html.HiddenFor(m => m.idOccurenceFormation);
<div style="width:550px;">
<br />
<span style="float:left"><b>Date de naissance :</b></span>
#Html.TextBoxFor(m => m.DateNaissanceChaine, new { Style = "float:right;width:350px;",id="datepicker" })
<br />
#Html.ValidationMessageFor(model => model.DateNaissanceChaine, "", new { #class = "text-danger"})
</div>
<input type="submit" class="btn" value="S'inscrire" style="width:200px; text-align:center;"/>
}
<script>
$(document).ready(function () {
$("#datepicker").datepicker({
format: 'DD-MM-YYYY'
});
});
</script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
So i don't know what im doing wrong according to the documentation it seems to be pretty simple to implement so maybe im just missing something important because the field only shows as a normal textbox
Any tip would be really helpful
Update
here is the error from the console :
TypeError: $(...).datepicker is not a function
Finally I found the problem it seems that jquery-ui was already loaded on the layout page and created problems since it was loaded twice
#Scripts.Render("~/bundles/jqueryui")
The problem is because you're trying to use the datepicker library before you've included it in the page. Put the <script> block containing your code after the references to jQuery.js and jQueryUI.js.
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$("#datepicker").datepicker({
format: 'DD-MM-YYYY'
});
});
</script>
Also note that you put the datepicker id on the validation label, not on the input element as it should be:
#Html.TextBoxFor(m => m.DateNaissanceChaine, new { Style = "float: right; width: 350px;", id = "datepicker })
<br />
#Html.ValidationMessageFor(model => model.DateNaissanceChaine, "", new { #class = "text-danger" })
I'd also strongly suggest you put the styling rules in classes, then add those classes in the HTML. putting inline styles in the HTML just makes the code muddy, and isn't a good separation of concerns
Move this script
<script>
$(document).ready(function () {
$("#datepicker").datepicker({
format: 'dd-mm-yy'
});
});
below Jquery Import
Also move the id="datepicker" to TextBoxFor().

Disable Div Contents Based on checkbox value using jquery

hi am developing mvc project using c#
currently am working on employee system model
I have designed view below like this
#Html.CheckBoxFor("value", new {data_divToDisable="SSLCSection",#class="SelectSection" })
<div id="SSLCSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
#Html.CheckBoxFor("value", new {data_divToDisable="PUCSection",#class="SelectSection" })
<div id="PUCSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
#Html.CheckBoxFor("value", new {data_divToDisable="GraduationSection",#class="SelectSection" })
<div id="GraduationSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
#Html.CheckBoxFor("value", new {data_divToDisable="PostGraduationSection",#class="SelectSection" })
<div id="PostGraduationSection" class="DisableDiv">
<table>
//Conntent goes here
</table>
</div>
here I need to disable sections when loading view based on checkbox value
like if checkbox is checked no need to disable that section otherwise it would be disable
I have written jquery like this
$(document).ready(function () {
$(".SelectSection").attr('checked', false,function(){
var id = $(this).find(".DisableDiv");
alert(id);
$(this).find(".DisableDiv").find('input, textarea, select,table').each(function () {
$(this).prop('disabled', true);
});
});
this is not doing anything for us
please help and your help would be greately appreciated
Please Note I have using data-Attribute to simplify the jquery and while each time loading the page it has to disable the sections based on checkbox value (hint:it has to disable if checkbox value is false )
You could try the follow, excuse the pseudo code.
HTML
<input class="SelectSection" type="checkbox" >hello1</input>
<div id="SSLCSection" class="DisableDiv" >
<input type="input">Test</input>
<textarea>Test1</textarea>
</div>
<br>
<input class="SelectSection" type="checkbox">hello2</input>
<div id="PUCSection" class="DisableDiv" >
<input type="input">Test2</input>
<textarea>Test12</textarea>
</div>
<br>
<input class="SelectSection" type="checkbox" checked>hello3</input>
<div id="PostGraduationSection" class="DisableDiv" >
<input type="input">Test3</input>
<textarea>Test3</textarea>
</div>
jQuery
$(document).ready(function () {
$(".SelectSection[type='checkbox']").each(function (i, o) {
if ($(o).is(":checked")) {
$(o).next('div').find('input,textarea').each(function (i, o) {
$(o).prop('disabled', true);
});
}
});
})
The above assumes that your next element after the relevant checkbox is the div in question which holds the elements that need to be disabled.

Using javascript/AJAX in MVC Razor View?

I am supposed to convert a form submission from MVC Razor submission to an Ajax submission but I am having trouble even using simple javascript functions in the view of the form (Add.cshtml).
For starters, I try to link the JS file that i want to use in the following way:
#section JavaScript
{
<script type="text/javascript" src="#Url.Content("/Scripts/ajax_submit.js")"></script>
}
The javascript file looks like this:
function dosubmit() {
$("#add_address").ajaxForm({ url: '~/Home/Add', type: 'post' })
alert("IT WORKS");
return false;// if it's a link to prevent post
}
and I have my form built in the following way:
#model MvcApplicationTest.Models.PersonModel
#section JavaScript
{
<script type="text/javascript" src="#Url.Content("/Scripts/ajax_submit.js")"></script>
}
#{
ViewBag.Title = "Hinzufügen";
}
<h2>Hinzufügen</h2>
<form id="add_address">
<div class="fieldrow">
#Html.LabelFor(x => x.Nachname)
#Html.TextBoxFor(x => x.Nachname)
#Html.ValidationMessageFor(x => x.Nachname)
</div>
<div class="fieldrow">
#Html.LabelFor(x => x.Vorname)
#Html.TextBoxFor(x => x.Vorname)
#Html.ValidationMessageFor(x => x.Vorname)
</div>
<div class="fieldrow">
#Html.LabelFor(x => x.Strasse)
#Html.TextBoxFor(x => x.Strasse)
#Html.ValidationMessageFor(x => x.Strasse)
</div>
<div class="fieldrow">
#Html.LabelFor(x => x.Hausnummer)
#Html.TextBoxFor(x => x.Hausnummer)
#Html.ValidationMessageFor(x => x.Hausnummer)
</div>
<div class="fieldrow">
#Html.LabelFor(x => x.Plz)
#Html.TextBoxFor(x => x.Plz)
#Html.ValidationMessageFor(x => x.Plz)
</div>
<div class="fieldrow">
#Html.LabelFor(x => x.Ort)
#Html.TextBoxFor(x => x.Ort)
#Html.ValidationMessageFor(x => x.Ort)
</div>
<!--Martin-->
<div class="fieldrow">
#Html.LabelFor(x => x.Email)
#Html.TextBoxFor(x => x.Email)
#Html.ValidationMessageFor(x => x.Email)
</div>
<input type="button" onclick="dosubmit()" value="Speichern" />
</form>
However, when I click the button nothing happens (it should pop up a window with the desired text).
I have tried to include the JS file into the _Layout.cshtml, but it still doesn't work.
Thanks for your help :)
You should just need to call .ajaxForm on the form itself when the document is ready. .ajaxForm by itself just prepares the form for ajax submission, so by the time the submit button has been pressed, it's already too late.
I'd remove the submit handler from the submit button (I'd also use an input of type submit here):
<input type="submit" value="Speichern" />
and add the following:
$(function () {
$("#add_address").ajaxForm({
url: '~/Home/Add',
beforeSubmit: function () {
alert('about to submit');
},
type: 'post'
});
});
Alternatively you could use .ajaxSubmit instead of .ajaxForm:
function dosubmit() {
$("#add_address").ajaxSubmit({ url: '~/Home/Add', type: 'post' });
alert("IT WORKS");
return false;// if it's a link to prevent post
}

html listbox click event(html helper class)

I am using asp .net mvc 4.0 ,vs2010
I have a listbox and textarea:
<div class="editor-list-field">
#Html.ListBoxFor(model => model.TableColumn, new SelectList(Model.TableColumn), new { #class = "listofcolumn" , name="listofcolumn"})
#Html.ValidationMessageFor(model => model.TableColumn)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Content)
</div>
<div class="editor-multiline-field">
#Html.TextAreaFor(model => model.Content, new { cols=60,#rows=10, #class = "textarea" name = "textarea"})
#Html.ValidationMessageFor(model => model.Content)
</div>
I am wondering, how can i generate an event like listbox_doubleclick(just for example: it could be like anything) and do what i have to.
I have to show the selected items from listbox to textarea for. And i want to do it simply.
I am surfing the net for a solution since yesterday, but could not apply anything to have the job done.
EDIT:
Some jQuery I have tried but no result:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">
$(function() {
​$('#listofcolumn')​.dblclick(function() { alert('clicked');
if ($(this).is(':selected')) {
var selectedId = $(this).val();
var selectedText = $(this).text();
alert(selectedText);
$('#textarea').val(selectedText);
}
});
});
</script>
You could use jQuery and dblClick
$('textarea').on('dblclick', function () {
alert('hola');
});

What's the best way to call a modal dialog in ASP.NET MVC using Twitter Bootstrap?

I'm currently using Twitter's Bootstrap toolkit on a new project and I had a question on the best way to use the modal dialog in ASP.NET MVC3.
Is the best practice to have a Partial that contains the modal's markup and then use javascript to render that onto the page or is there a better approach?
Here goes my little tutorial which demonstrates Twitter's Bootstrap (2.x) modal dialog that works with forms and partials in ASP.Net MVC 4.
To download similar project but targeting MVC 5.1 and Bootstrap 3.1.1 please visit this site.
Start with an empty MVC 4 Internet template.
Add reference to Bootstrap using NuGet
In the App_Start/BundleConfig.cs add the following lines:
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js"));
bundles.Add(new StyleBundle("~/Content/bootstrap").Include(
"~/Content/bootstrap.css",
"~/Content/bootstrap-responsive.css"));
In the Views/Shared/_Layout.cshtml
modify the #styles.Render line so it will look like:
#Styles.Render("~/Content/css", "~/Content/themes/base/css", "~/Content/bootstrap")
and the #Scripts.Render line:
#Scripts.Render("~/bundles/jquery", "~/bundles/jqueryui", "~/bundles/bootstrap")
So far we have Bootstrap prepared to work with MVC 4 so let's add a simple model class MyViewModel.cs to the /Models folder:
using System.ComponentModel.DataAnnotations;
namespace MvcApplication1.Models
{
public class MyViewModel
{
public string Foo { get; set; }
[Required(ErrorMessage = "The bar is absolutely required")]
public string Bar { get; set; }
}
}
In the HomeController Add the following lines:
using MvcApplication1.Models;
//...
public ActionResult Create()
{
return PartialView("_Create");
}
[HttpPost]
public ActionResult Create(MyViewModel model)
{
if (ModelState.IsValid)
{
try
{
SaveChanges(model);
return Json(new { success = true });
}
catch (Exception e)
{
ModelState.AddModelError("", e.Message);
}
}
//Something bad happened
return PartialView("_Create", model);
}
static void SaveChanges(MyViewModel model)
{
// Uncommment next line to demonstrate errors in modal
//throw new Exception("Error test");
}
Create new Partial View in the Views/Home folder and name it _Create.cshtml:
#using MvcApplication1.Models
#model MyViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Create Foo Bar</h3>
</div>
#using (Html.BeginForm("Create", "Home", FormMethod.Post, new { #class = "modal-form" }))
{
#Html.ValidationSummary()
<div class="modal-body">
<div>
#Html.LabelFor(x => x.Foo)
#Html.EditorFor(x => x.Foo)
#Html.ValidationMessageFor(x => x.Foo)
</div>
<div>
#Html.LabelFor(x => x.Bar)
#Html.EditorFor(x => x.Bar)
#Html.ValidationMessageFor(x => x.Bar)
</div>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Undo</button>
<button class="btn btn-primary" type="submit">Save</button>
</div>
}
In the Home/Index.cshtml remove the default content from the template and replace it with following:
#{
ViewBag.Title = "Home Page";
}
<br />
<br />
<br />
#Html.ActionLink("Create", "Create", null, null, new { id = "btnCreate", #class = "btn btn-small btn-info" })
<div id='dialogDiv' class='modal hide fade in'>
<div id='dialogContent'></div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
//Optional: turn the chache off
$.ajaxSetup({ cache: false });
$('#btnCreate').click(function () {
$('#dialogContent').load(this.href, function () {
$('#dialogDiv').modal({
backdrop: 'static',
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#dialogDiv').modal('hide');
// Refresh:
// location.reload();
} else {
$('#dialogContent').html(result);
bindForm();
}
}
});
return false;
});
}
</script>
}
If you run your application, a nice Bootstrap modal will appear after clicking the Create button on the Home page.
Try to uncomment the SaveChanges() //throw line in HomeController.cs to prove that your controller handled errors will appear correctly in the dialog.
I hope that my sample clarifies a bit whole process of incorporating Bootstrap and creating modals in the MVC application.
Great example, I had to modify slightly for MVC 5 and Bootstrap 3.3.7, I changed the target div tags to the following, otherwise I was just getting the grey background and no modal dialog. Hope this helps someone.
<div id='dialogDiv' class='modal fade' tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div id='dialogContent'></div>
</div>
</div>
</div>
Thanks #zjerry the solution is great but jQuery validation does not work, in order to fix you need to change the function bindForm as follow:
function bindForm(dialog) {
$.validator.unobtrusive.parse('form');
$('form', dialog).submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#dialogDiv').modal('hide');
// Refresh:
// location.reload();
} else {
$('#dialogContent').html(result);
bindForm();
}
}
});
return false;
});
}
Notice the first line of the function, because the form is loaded after jQuery validation was initialized.
Many thanks
This really depends on your design, but you should have a template for the modals.
On a single web app for example, you should have a template lying around that you would create a new instance from each time.
Usually on a normal website you would want to store this template inside a js creation function, so that you won't have to send the file to the user each time via http, and they can have it cached.

Categories