jquery tabs inside modal popup using MVChelper class - asp.net-mvc

I am using a MVC helper class to display modal popup . my requirement is to show tabs inside this modal popup... here is what is did
My helper class
public static MvcHtmlString DialogROFormLink(this HtmlHelper htmlHelper, string linkText, string dialogContentUrl,
string dialogTitle, string updateTargetId, string updateUrl, string l_intHeight, string l_intWidth, string l_strFrmLinkPost )
{
TagBuilder builder = new TagBuilder("a");
builder.SetInnerText(linkText);
builder.Attributes.Add("href", dialogContentUrl);
builder.Attributes.Add("data-dialog-title", dialogTitle);
builder.Attributes.Add("data-update-target-id", updateTargetId);
builder.Attributes.Add("data-update-url", updateUrl);
builder.Attributes.Add("data-dialog-height", l_intHeight );
builder.Attributes.Add("data-dialog-width", l_intWidth );
builder.Attributes.Add("data-dialog-frmLink", l_strFrmLinkPost);
// Add a css class named dialogLink that will be
// used to identify the anchor tag and to wire up
// the jQuery functions
builder.AddCssClass("ROdialogLink");
return new MvcHtmlString(builder.ToString());
}
The JS file
$(function () {
// Don't allow browser caching of forms
$.ajaxSetup({ cache: false });
// Wire up the click event of any current or future dialog links
$('.ROdialogLink').live('click', function () {
var element = $(this);
// Retrieve values from the HTML5 data attributes of the link
var dialogTitle = element.attr('data-dialog-title');
var updateTargetId = '#' + element.attr('data-update-target-id');
var updateUrl = element.attr('data-update-url') + "?id=" + Math.floor(Math.random() * 1000);
// Generate a unique id for the dialog div
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000)
var dialogDiv = "<div id='" + dialogId + "'></div>";
var lheight = element.attr('data-dialog-height');
var lwidth = element.attr('data-dialog-width');
var l_frmPost = element.attr('data-dialog-frmLink');
// Load the form into the dialog div
$(dialogDiv).load(this.href, function () {
$(this).dialog(
{
modal: true,
resizable: false,
width: lwidth,
height: lheight,
title: dialogTitle,
cache: false,
type: 'get',
buttons:
{
"Save": function () {
// Manually submit the form
var form = $('form', this);
$(form).submit();
},
"Cancel": function ()
{ $(this).dialog('destroy'); }
},
show: {
effect: "blind",
duration: 200
},
hide: {
effect: "blind",
duration: 200
}
})
// Enable client side validation
$.validator.unobtrusive.parse(this);
// Setup the ajax submit logic
wireUpForm(this, updateTargetId, updateUrl, l_frmPost);
});
return false;
});
});
function wireUpForm(dialog, updateTargetId, updateUrl, l_frmPost) {
$('form', dialog).submit(function () {
// Do not submit if the form
// does not pass client side validation
if (!$(this).valid())
return false;
$(dialog).dialog('close');
// Client side validation passed, submit the form
// using the jQuery.ajax form
return false;
});
}
Here is my view in which I have added the tabs script
<script>
$(function () {
$("CalendarTabs").tabs();
});
</script>
#using (Html.BeginForm())
{
<div id="CalendarTabs">
<ul>
<li>Estimate</li>
<li>Address/Phone/Insurance</li>
</ul>
<div id="CalTab-1">
</div>
<div id="CalTab-2">
</div>
</div>
}
I tried to show modal popup without using helper class to show popup including tabs and works fine. But fails in this case.
Please Help me! Thanks

Related

Jquery UI drag and drop - dragged item dissapears when dropped only on mobile

I am trying to get drag and drop working properly and on desktop of laptop pc it is fine. However, on a mobile device, when I drag and drop, when dropped, the dragged item dissapears underneath (i think) everything else and I really am unable to work out why.
I have uploaded a page showing the problem to http://mailandthings.co.uk/dam1/
I have tried setting the zindex in the draggable code and that makes no difference
var $dragContainer = $("div.drag-container");
var $dragItem = $("div.drag-item");
$dragItem.draggable({
cursor: "move",
snap: "div.drag-container",
snapMode: "inner",
snapTolerance: 10,
helper: "clone",
handle: "i",
zIndex: 10000
});
$dragContainer.droppable({
drop: function (event, ui) {
var $elem = $(event.toElement);
var obj = {
posX: event.pageX - $dragContainer.offset().left - event.offsetX,
posY: event.pageY - $dragContainer.offset().top - event.offsetY,
data: $elem.data(),
html: $elem.html()
};
addElement(obj);
masterPos.push(obj);
}
});
function addElement(obj) {
var $child = $("<div>");
$child.html("<i>" + obj.html + "</i>").addClass("drop-item drop-item-mobile");
$child.attr("data-type", obj.data.type);
$child.css({
top: obj.posY,
left: obj.posX
});
$dragContainer.append($child);
}
If it using jQuery UI Touch Punch 0.2.3
Does anyone have any ideas?
There was sort of a logistical issue that I found. Based on your code, I could identify the following state / logic:
User drags an item (A, B, C) to the car image to indicate a Dent, Scratch, or Heavy Damage
The Drop Point indicates where the Type of damage is located
When the dragged item is dropped, a new object should be created that indicates the Type and stores the location on the car map
This new object replaces the dragged item and is appended to the container
To expand on this, you have the following code that is the dragged element, for example:
<div class="drag-item ui-draggable" style="">
<i data-type="A" class="ui-draggable-handle">A</i>Dent
</div>
This is important when creating the new object. In your current code, you're requesting data from an object that does not have any data attributes, $elem.data(). Remember that this is the <div> that contains the <i> that has the attribute. So data is null or undefined. You will want to capture the data from the child element: $elem.find("i").data().
Also, since you append all the HTML to your new object, you make a double wrapped element. $child will look like:
<div class="drop-item drop-item-mobile">
<i>
<div class="drag-item ui-draggable" style="">
<i data-type="A" class="ui-draggable-handle">A</i>Dent
</div>
</i>
</div>
I do not think this was your intention. I suspect your intention was to create:
<div class="drop-item drop-item-mobile">
<i>A</i>
</div>
Here is an example of all this: https://jsfiddle.net/Twisty/g6ojp4ro/40/
JavaScript
$(function() {
var theForm = document.forms.form1;
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
var masterPos = [];
$("#hidpos").val('');
var $dragContainer = $("div.drag-container");
var $dragItem = $("div.drag-item");
$dragItem.draggable({
cursor: "move",
snap: "div.drag-container",
snapMode: "inner",
snapTolerance: 10,
helper: "clone",
handle: "i",
zIndex: 10000
});
$dragContainer.droppable({
drop: function(event, ui) {
var $elem = ui.helper;
var type = ui.helper.find("i").data("type");
var $child = $("<div>", {
class: "drop-item drop-item-mobile"
}).data("type", type);
$("<i>").html(type).appendTo($child);
$child.appendTo($dragContainer).position({
of: event
});
var obj = {
posX: $child.offset().top,
posY: $child.offset().left,
data: $child.data(),
html: $child.prop("outerHTML")
};
masterPos.push(obj);
}
});
$("map").imageMapResize();
// Save button click
$('#form1').submit(function(e) { //$("#btnsave").click(function () {
if (masterPos.length == 0) {
$("#spnintro").html("Oops!");
$("#spninfo").html("No position data was entered");
$("#dvinfo").fadeTo(5000, 500).slideUp(500, function() {});
} else {
$("#hidpos").val(JSON.stringify(masterPos));
$.ajax({
url: '/handlers/savepositions.ashx',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
success: function(data) {
$("#spnintro").html("Success!");
$("#spninfo").html("Position data has been saved");
$("#dvinfo").fadeTo(5000, 500).slideUp(500, function() {});
}
});
}
e.preventDefault();
});
});
Tested with Mobile client at: https://jsfiddle.net/Twisty/g6ojp4ro/40/show/ and is working as expected.
Hope that helps.

ASP.NET MVC 5: Client Validation is not working for a view model (annotations) [duplicate]

I have JQuery popups and i want to put required field validations on it and for this i have set required attributes in model and have also set the validation message for them in the view but that required field validations are not working on popups. Required field validation is working fine on forms other than JQuery Popups....Please guide me that what should i do to tackle this issue...Following is my code.
Model
[Display(Name = "Material Code")]
[Required(ErrorMessage = "*")]
public string MaterialCode { get; set; }
View
<li>
#Html.LabelFor(m => m.MaterialCode)
#Html.TextBoxFor(m => m.MaterialCode)
#Html.HiddenFor(m => m.MaterialCodeId)
</li>
and following is my cod eto open a JQuery popup.
$('#btnAddCharge').on('click', function (event) {
event.preventDefault();
var actionURL = '#Url.Action("Edit", "Charges", new { Id = 0, #ticketId = #TicketId, UserId = UserId })';
$(dialogBox).dialog({
autoOpen: false,
resizable: false,
title: 'Edit',
modal: true,
show: "blind",
width: 'auto',
hide: "blind",
open: function (event, ui) {
$(this).load(actionURL, function (html) {
$('form', html).submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (res) {
if (res.success) {
$(dialogBox).dialog('close');
}
}
});
return false;
});
});
}
});
$(dialogBox).dialog('open');
});
The validator is parsed when the page is initially loaded. When you add dynamic content you need to reparse the validator. Modify your script to include the following lines after the content is loaded
$(this).load(actionURL, function (html) {
// Reparse the validator
var form = $('form');
form.data('validator', null);
$.validator.unobtrusive.parse(form);
$('form', html).submit(function () {
....
Side note: The code you have shown does not include #Html.ValidationMessageFor(m => m.MaterialCode) but I assume this is included.

Autocomplete results will not be displayed inside asp.net mvc partial view

I have the following script that is rendered inside my _layout view:-
$(document).ready(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"),
minLength: 1,
delay: 1000
});
});
});
and i added the following field to apply autocomplete on it:-
<input name="term" type="text" data-val="true"
data-val-required= "Please enter a value."
data-autocomplete-source= "#Url.Action("AutoComplete", "Staff")" />
now if i render the view as partial view then the script will not fire, and no autocomplete will be performed, so i added the autocomplete inside ajax-success as follow:-
$(document).ready(function () {
$(document).ajaxSuccess(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"),
minLength: 1,
delay: 1000
});
});
});
});
now after adding the AjaxSuccess the action method will be called, and when i check the response on IE F12 developers tools i can see that the browser will receive the json responce but nothing will be displayed inside the field (i mean the autocomplete results will not show on the partial view)?
EDIT
The action method which is responsible for the autocomplete is:-
public async Task<ActionResult> AutoComplete(string term)
{
var staff = await unitofwork.StaffRepository.GetAllActiveStaff(term).Select(a => new { label = a.SamAccUserName }).ToListAsync();
return Json(staff, JsonRequestBehavior.AllowGet);
}
EDIT2
here is the script which is responsible to show the modal popup:-
$(document).ready(function () {
$(function () {
$.ajaxSetup({ cache: false });
//$("a[data-modal]").on("click", function (e) {
$(document).on('click', 'a[data-modal]', function (e){
$('#myModalContent').css({ "max-height": screen.height * .82, "overflow-y": "auto" }).load(this.href, function () {
$('#myModal').modal({
//height: 1000,
//width: 1200,
//resizable: true,
keyboard: true
}, 'show');
$('#myModalContent').removeData("validator");
$('#myModalContent').removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse('#myModalContent');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", "disabled");
$('#progress').show();
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.ISsuccess) {
$('#myModal').modal('hide');
$('#progress').hide();
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", false);
location.reload();
// alert('www');
} else {
$('#progress').hide();
$('#myModalContent').html(result);
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", false);
bindForm();
}
}
});
}
else {
$('.btn.btn-primary,.btn.btn-danger').prop("disabled", false);
$('#progress').hide();
return false;
}
return false;
});
}
});
First, you don't need to wrap you ajaxSuccess fucntion in ready function.
Second, it's better to use POST when you get Json from server.
I tried to seproduce your problem, but have no luck.
Here how it works in my case(IE 11, MVC 4)
script on _Layout:
$(document).ajaxSuccess(function () {
$("input[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: function (request, response) {
$.post(target.attr("data-autocomplete-source"), request, response);
},
minLength: 1,
delay: 1000
});
});
});
Controller method:
[HttpPost]
public JsonResult AutoComplete()
{
return Json(new List<string>()
{
"1",
"2",
"3"
});
}
Partial View html:
<input name="term" type="text" data-val="true"
data-val-required="Please enter a value."
data-autocomplete-source="#Url.Action("AutoComplete", "Stuff")" />
UPDATE:
I find out what your problem is. Jquery autocomplete needs array of objects that have lable and value properties. So if you change your controller code like this and it will work.
public async Task<ActionResult> AutoComplete(string term)
{
var staff = await unitofwork.StaffRepository.GetAllActiveStaff(term)
.Select(a => new { label = a.SamAccUserName, value = a.SamAccUserName })
.ToListAsync();
return Json(staff, JsonRequestBehavior.AllowGet);
}
Also you can do it on client side with $.map jquery function you can see example here

jQuery Dialog leaving page on getScript() call

I have the following jQueryUI Dialog element.. I'm trying to make an AJAX call to populate the form when it launches.. I'm also using Ajax to load the actual form..
Problem happens when the populateForm method is invoked..
The Dialog disappears and the browser leaves my page when the $.getScript method is invoked..
any ideas?
I'm stuck!
DIALOG
$('#highValueSurvey').dialog({
autoOpen: false,
modal: true,
width: 900,
resizable: false,
open: function(event, ui) {
$("#highValueSurvey").load('/longstoryshort/forms/high.html');
$("#highValueSurvey").dialog('option', 'position', 'center');
populateForm('#FY12-Q1-AM-ALL-ECMC-VML-ProfilingForm');
},
buttons: {
'Submit': function() {
var path = $(this).data('link').href; // Get the stored result
doAjaxPost('#FY12-Q1-AM-ALL-ECMC-VML-ProfilingForm');
setCookie(highValueCookieName, -1, 1000);
window.location.href = path;
}
}
});
CLICK EVENT
$("a.clickHighValueAsset").click(function(e) {
cookie_value = getCookie(highValueCookieName);
if (cookie_value != -1) {
e.preventDefault();
e.stopImmediatePropagation();
$("#highValueSurvey")
.data('link', this)// bind the url from the HREF to the dialog UI for redirect later
.dialog('open');
}
else {
return true;
}
});
POPULATE METHOD
function populateForm(formName) {
if (typeof eMail != 'undefined') {
elqServlet = window.location.protocol + '//' + window.location.host + '/longstoryshort/forms/lookup.jsp?email=';
$.getScript(elqServlet + eMail, function() {
$(':input', '#' + formName).each(function() {
var field = '#' + this.name + '';
$(field).val(GetElqContentPersonalizationValue(this.name));
});
});
}
}
Wrap the populateForm() which is async.. And then call the window.href redirect within it's success callback!
Example:
'Submit': function() {
$.ajax({
type: "POST",
async: true,
url: $("#FY12-Q1-AM-ALL-ECMC-VML-ProfilingForm").attr('action'),
data: $("#FY12-Q1-AM-ALL-ECMC-VML-ProfilingForm").serialize()
});
setCookie(highValueCookieName, -1, 1000);
$(":button:contains('Submit')").hide();
$("#highValueSurvey").load('/longstoryshort/forms/confirmation.html');
$("#highValueSurvey").dialog({
close: function() {
var path = $(this).data('link').href; // Get the stored result
window.location.href = path;
}
});
}

How to create a dialog using jquery-ui without html div specified

Using jquery-ui to create a dialog is pretty easy:
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
...but one still needs a div in the HTML for this to work. In Dojo:
var dlg = new dijit.Dialog({
title:"dialog",
style: "width:30%;height:300px;"
});
dlg.show();
would just do the trick without anything specified in the html section, can jquery-ui do this? (I have to use jquery-ui here)
Thanks,
David
While I'm not sure why you would want to open a dialog with no content, you could easily create a new one on the fly and invoke the jquery dialog against it:
$("<div>hello!</div>").dialog();
basic code
var d = $("#someId");
if (d.length < 1)
d = $("<div/>").attr("id", "someId")
.appendTo("body");
else
d.dialog('destroy');
d.html('some message')
.dialog({ some_options })
.dialog("open");
and you can probably put rap this in an extension method.
Update (my full code listing)
(function($) {
$.extend({
showPageDialog: function (title, content, buttons, options) {
/// <summary>Utility to show a dialog on the page. buttons and options are optional.</summary>
/// <param name="buttons" type="Object">Dialog buttons. Optional, defaults to single OK button.</param>
/// <param name="options" type="Object">Additional jQuery dialog options. Optional.</param>
if (!buttons)
buttons = { "Ok": function () { $(this).dialog("close"); } };
var defOptions = {
autoOpen: false,
modal: true,
//show: "blind",
//hide: "explode",
title: title,
buttons: buttons
};
if (options)
defOptions = $.extend(defOptions, options);
var pd = $("#pageDialog");
if (pd.length < 1)
pd = $("<div/>").attr("id", "pageDialog")
.appendTo("body");
else
pd.dialog('destroy');
pd.html(content)
.dialog(defOptions)
.dialog("open");
}
}//end of function show...
)//end of extend Argument
})(jQuery)
Sample Usage
$.showPageDialog(title, message, {
"Yes": function () {
$(this).dialog("close");
// do something for 'yes'
},
"No": function () {
// do something for no
}
}
var div = document.createElement('div');
div.innerHTML = "Hello World";
$(div).dialog();
Juan Ayalas solution should work for modal Dialogs.
For a non modal dialog it would be better to track the id inside the function.
I use the following code which is not perfect but should work to ensure that the
id is unique. The code is nearly equal to Juan Ayalas example but uses a counter to avoid a duplicate id. (Furthermore I deleted the OK-Button as default).
(function($)
{
var dCounter=0; //local but "static" var
$.extend({
showPageDialog: function (title, content, buttons, options) {
/// <summary>Utility to show a dialog on the page. buttons and options are optional.</summary>
/// <param name="buttons" type="Object">Dialog buttons. Optional, defaults to nothing (single OK button).</param>
/// <param name="options" type="Object">Additional jQuery dialog options. Optional.</param>
if (!buttons)
buttons = {}; //{ "Ok": function () { $(this).dialog("close"); } };
var defOptions = {
autoOpen: false,
width: "auto",
modal: false,
//show: "blind",
//hide: "explode",
title: title,
buttons: buttons
};
if (options)
defOptions = $.extend(defOptions, options);
dCounter++;
//console.log("dCounter is " + dCounter);
var pdId = "#pageDialog"+dCounter;
var pd = $(pdId);
if (pd.length < 1)
pd = $("<div/>").attr("id", pdId)
.appendTo("body");
else
pd.dialog('destroy');
pd.html(content)
.dialog(defOptions)
.dialog("open");
}//end of function showPageDialog
}//end of extend options
)//end of extend argument
}//end of function definition

Resources