How do I postback from a JQuery dialog to another ASP .NET page? - jquery-ui

I am using ASP .NET to display a JQuery dialog that has a few input fields. I now need these fields to submitted to an action method like how a normal HTML submit button would work on an ASP .NET MVC application. How do I accomplish this?
This is my form data:
All form fields are required.
<%Html.BeginForm("AddUser", "User"); %>
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" id="name" />
<label for="email">Email</label>
<input type="text" name="email" id="email" value="" />
<label for="password">Password</label>
<input type="password" name="password" id="password" value="" />
</fieldset>
<%Html.EndForm(); %>
"
And this is my script:
$(function() {
$("#dialog").dialog({
bgiframe: true,
height: 400,
width: 600,
modal: true,
buttons: {
'Create user account': function() {
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
});
});

Add a line to your code that submits the form:
$(function() {
$("#dialog").dialog({
bgiframe: true,
height: 400,
width: 600,
modal: true,
buttons:
{
'Create user account': function() {
$('#yourDialogFormID').submit(); // add this line
$(this).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
});
});
You can set the ID by giving the Html.BeginForm() method an argument for htmlAttributes (type object if I remember the structure correctly - look for it in the overload methods in IntelliSense).

You can harvest the data from your form and post it using jQuery.post
$.post("someform.aspx", { name: $("#name").val(), email: $("#email").val() } );

Related

Laravel 5.5 autocomplete method returns a 500 error in one place not another

I have a simple form to get an autocomplete of an author's name from a table of several thousand.
In my simple form I have:
<form>
<div class="ui-widget">
<label for="authors">authors: </label>
<input id="authors" value="">
</div>
</form>
The javascript is:
<script>
$(function()
{
$( "#authors" ).autocomplete({
source: "autocompleteAuthors",
minLength: 3,
select: function(event, ui) {
$('#q').val(ui.item.value);
}
});
});
</script>
I have a route pointing to a controller:
Route::get('autocompleteAuthors','AutoCompleteController#authors')->name('autocompleteAuthors');
and a function in the controller:
public function authors()
{
$term = Input::get('term');
$results = array();
$queries = DB::table('author')
->where('name', 'LIKE', '%'.$term.'%')
->take(5)->get();
foreach ($queries as $query)
{
$results[] = [ 'id' => $query->id, 'value' => $query->name];
}
return Response::json($results);
}
This works fine.
In a form to edit a quote (part of the edit could be the author) I have the following:
<div class="ui-widget">
<label for="author" style="width:10%">author:</label>
<input id="author" name="author" value="{{ $author[0]->name }}" style="width:50%">
</div>
and the javascript is:
<script>
$(function()
{
$( "#author" ).autocomplete({
source: "autocompleteAuthors",
minLength: 3,
select: function(event, ui) {
$('#q').val(ui.item.value);
}
});
});
</script>
So they are both sending "term" to the same route yet in the second case I get a 500 error.
Can't see any reason for this!
I managed to sort it out. If you set the value in
<input id="author" name="author" value="{{ $author[0]->name }}" style="width:50%">
everything fails.
The answer is very simple: set it after the ui is called.
So my form includes:
<div class="ui-widget">
<label for="author" style="width:10%">author:</label>
<input id="author" name="author" style="width:50%">
</div>
and I invoke the ui with
$(function() {
$( "#author" ).autocomplete({
source: "{{ route('autocompleteAuthors') }}",
minLength: 3,
select: function(event, ui) {
$('#q').val('ui.item.value');
}
});
});
and then I add the initial value:
$( "#author" ).val("{{ $author[0]['name'] }}");

Knockout-Validation Show Template before input

I have a simple JSFiddle example http://jsfiddle.net/b625zeL5/6/
<script>
ko.validation.init({
registerExtenders: true,
messagesOnModified: true,
insertMessages: false,
parseInputAttributes: true,
messageTemplate: 'errorTemplate',
decorateInputElement: true,
errorElementClass: 'error'
}, true);
var ViewModel = function(){
this.email = ko.observable("")
.extend({ required: true })
.extend({ email: true });
this.password = ko.observable("")
.extend({ required: true });
};
var viewModel = new ViewModel();
viewModel.errors = ko.validation.group(viewModel);
ko.applyBindings(viewModel);
</script>
<form>
<span data-bind="validationMessage: email"></span>
<input type="text" id="email" data-bind="value: email, validationElement: email, valueUpdate:'keyup'" /> <br/>
<span data-bind="validationMessage: password"></span>
<input type="text" id="password" data-bind="value: password, validationElement: password, valueUpdate:'keyup'"/>
</form>
<script type="text/html" id="errorTemplate">
Error: <span data-bind="validationMessage: field">X</span>
</script>
As you can see - I disabled insertMessages because I need error messages to show before input field. Thus I added span with "data-bind="validationMessage: email"" before each text input.
I defined in validation config
messageTemplate: 'errorTemplate'
but error messages still plain text. How can I get messageTemplate to work?
Because you turned off insertMessages, knockout validation won't use your error message template and it will use what you inserted above each field.
You have two options:
For each observable that has a validation, add a custom error message.
Example 1:
this.password = ko.observable("")
.extend({ required: {
params: true,
message: "Error: This is required"
}
});
Change your error template to something like this:
Example 2:
<script type="text/html" id="errorTemplate">
Error: <span data-bind="validationMessage: error_field"></span>
</script>
.. and inside the form, you can call the template like:
<form>
<!-- ko template: { name: 'errorTemplate', data: { error_field: email } }-->
<!-- /ko -->
<input type="text" id="email" data-bind="value: email, validationElement: email, valueUpdate:'keyup'" /> <br/>
...
...
see jsfiddle here with example 2 in action : http://jsfiddle.net/mhgv48e8/
Hope it helps :)

Kendo Template Invalid in Grid

What am I doing wrong? I get the following error. I am using MVC but not using the MVC wrappers.
Uncaught Error: Invalid template:'
<form action="/Intranet/GalleryFile/Edit" data-ajax="true" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-update="#slideoutmenu" id="form1" method="post"> <input type="hidden" id="fileID" name="fileID" value='#= fileID #' />
<input type="submit" value="Save" class="btn btn-default" />
</form> ' Generated code:'var o,e=kendo.htmlEncode;with(data){o='\n<form action="/Intranet/GalleryFile/Edit" data-ajax="true" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-update="';slideoutmenu" id="form1" method="post"> <input type="hidden" id="fileID" name="fileID" value=';o+='= fileID ';' />
<input type="submit" value="Save" class="btn btn-default" />
</form> ;o+=;}return o;'
JavaScript:
$(document).ready(function () {
var dsGalleryItemFile = new kendo.data.DataSource({
transport: {
read: "#Url.Content("~/Intranet/GalleryItemFile/ListFiles/")#Model.galleryItemID"
},
// determines if changes will be send to the server individually or as batch
batch: false,
schema: {
model: {
id: "fileID",
fields: {
fileID: {
nullable: true
},
filename: {},
fileType: { defaultValue: {fileTypeID: 1, fileType: "Web JPEG"} },
fileType: {},
width: { type: "number" },
height: { type: "number" },
}
}
}
});
$("#gvGalleryItemFile").kendoGrid({
columns: [{
field: "filepath",
title: "File Upload",
width:"250px",//,
//template: "<img src='#=filepath.filepath#' />"
}, {
field: "fileType",
title: "File Type",
template: "#=fileType.fileType#",
}, {
field: "width",
title: "Width(px)",
format: "{0:n0}",
width: "110px"
}, {
field: "height",
title: "Height(px)",
format: "{0:n0}",
width: "110px"
}, {
field: "fileID",
title: "",
template: kendo.template($("#gridEditButtonTemplate").html())
}],
dataSource: dsGalleryItemFile
});
});
Template:
<script type="text/x-kendo-template" id="gridEditButtonTemplate">
#using (Ajax.BeginForm("Edit", "GalleryFile", null, new AjaxOptions { UpdateTargetId = "slideoutmenu", InsertionMode = InsertionMode.Replace, HttpMethod = "Post" }))
{
<input type="hidden" id="fileID" name="fileID" value='#= fileID #' />
<input type="submit" value="Save" class="btn btn-default" />
}
</script>
This isn't even reaching the MVC side of things so I am not including that code. It just won't read the template into my grid column.
The # character has a special meaning in kendo templates and thus it has to be escaped if you want to use it as a regular character.
Your Ajax.BeginForm is creating the attribute
data-ajax-update="#slideoutmenu"
which is what breaks your template. It should be
data-ajax-update="\#slideoutmenu"
I'm not sure if there is a way around this using the Html helpers. The easiest fix would be using plain Html instead.

How to put a Kendo control into a Kendo template?

I'm trying to put a NumericTextBox into a Kendo template.
Here is the code:
<script type="text/x-kendo-template" id="clone-wizard-template">
<p>Bitte wählen Sie, wie viele Male Sie möchten <br />die Aktionsgruppe fortschreiben:
</p>
#(Html.Kendo().NumericTextBox()
.Name("custom")
.Value(10)
.ToClientTemplate())
<br />
/*some other lines*/
</script>
Which is strangely rendered into this:
<script type="text/x-kendo-template" id="clone-wizard-template">
<p>Bitte wählen Sie, wie viele Male Sie möchten <br />die Aktionsgruppe fortschreiben:
</p>
<input class="k-input" id="custom" name="custom" type="number" value="10" /><script>
jQuery(function(){jQuery("\#custom").kendoNumericTextBox({});});
<\/script>
<br />
/*some other lines*/
</script>
I cannot understand from where comes </script> tag...
I'm loading a template into a modal window by using this code:
editAktionsgruppen.kendoWindow = $("<div />").kendoWindow({
title: "Bestätigen",
resizable: false,
visable: false,
modal: true
}).html($("#clone-wizard-template").html()).data("kendoWindow");
Isn't this a correct way to input a control in the template?
I would probably write it like this:
var popUpWindow = $("<div />").kendoWindow({
title: "Bestätigen",
resizable: false,
content: {
template: kendo.toString($('#clone-wizard-template').html())
},
visable: false,
modal: true
});
//add kendo validation to popup window
$('#my-form').kendoValidator();
//initialise the numeric textbox (you could specify a class on the input and find
//by that instead instead of using an id)
$('#NumInput').kendoNumericTextBox();
//wire-up an ok/submit button
$(popUpWindow).find('.t-button').on('click', function() {
var validator = $('#my-form').data('kendoValidator');
if(valiator.validate())
{
// do stuff
}
});
//show the window
$(popUpWindow).data('kendoWindow').center().open();
then the client template:
<script type="text/x-kendo-template" id="clone-wizard-template">
<form id="my-form">
<p>Bitte wählen Sie, wie viele Male Sie möchten <br />die Aktionsgruppe fortschreiben:
</p>
<input id="NumInput" name="NumInput" type="number" required data-required-msg="number required" />
<br />
/*some other lines*/
<button type="button" class="t-button">my button</button>
</form>
</script>

JQuery UI Dialogs and divs in separate files

I am working on a project and I'd like to use Jquery UI for some of the forms like adding and updating stuff instead of normal pages. I designed the dialog, set up the form but it works only if the form/div is in the same file as the button. I am using CodeIgniter for this project by the way.
So I have few questions:
Does JQuery UI dialogs support using divs from separate files? (if the button is not in the same file as the form/div)
If it does, how can I use a div that is in a different file (instead of placing the div in the same file with the button where I have few other components)?
Example:
index.php
<body>
<input type="button" id="add_new" value="add new" />
</body>
form.php
<body>
<div id='"new_user_form'>
<input type="text" id="name" />
<input type="text" id="username" />
<input type="password" id="password" />
<input type="button" id="add_user" value="add new" />
</div>
</body>
custom.js
$(document).ready(function ()
{
$('# add_new ').click (function ()
{
$("# new_user_form ").dialog
({
title: 'Add new user',
height: 400,
width: 600,
resizable: false,
modal: true,
draggable: false,
buttons:
[
{
text: 'add new',
id: ' add_user ',
click: function()
{
alert("Testing 123...");
}
},
{
text: 'cancel',
click: function()
{
$(this).dialog('close');
}
}
]
})
})
})
thanks for reading, hope someone can help me!
It is totally possible, but I noticed a few errors :
You wrote id='"new_user_form', it could make " part of the id.
Same for this selector $('# add_new ') and $("# new_user_form "), trim it.
You declare your .dialog() on a div that is probably not yet in the DOM, since you load it from form.php.
do not use body in a page you will append, or you might end up with two body tags.
You could load form.php with something similar to .load("form.php"), you will have to remove those body tags from form.php :
$("body").load("form.php",function()
{
$("#new_user_form").dialog(
{
// your options
});
});
Or you can also declare a dialog and replace its content when you need to, you will have to remove body and div from your form.php in order to use this code :
<div id='new_user_form' style='display:none;'></div> <!-- somewhere in your index.php -->
// when document ready is triggered
$("#new_user_form").dialog();
// when you need it :
$("#new_user_form").load("form.php",function(){$("#new_user_form").dialog("open")});
I don't know why the load() function didn't work but I found a better way to fix this problem.
How I did it:
users_view.php (previously index.php)
<body>
<input type="button" id="add_new" value="add new" />
<div id="new_user_form">
<?php $this->load->view('add_user_form'); ?>
</div>
</body>
add_user_form.php (previously form.php)
<div>
<input type="text" id="name" />
<input type="text" id="username" />
<input type="password" id="password" />
<input type="button" id="add_user" value="add new" />
<input type="button" id="cancel" value="cancel" />
</div>
custom.js
$(document).ready(function ()
{
$("#new_user_form").dialog
({
title: 'Add new userт',
height: 400,
width: 600,
resizable: false,
modal: true,
draggable: false,
autoOpen: false
})
$('#add_new').click (function ()
{
$("#new_user_form").dialog("open");
})
$('#cancel').click(function()
{
$("#new_user_form").dialog("close");
});
})
Thanks for the answers! I hope this will help other people :)

Resources