So I have a requirement to auto submit a form upon edit of a set textbox within a form.
using (Ajax.BeginForm(new AjaxOptions() { UpdateTargetId = "refresh", InsertionMode = InsertionMode.Replace }, new { #id = "refresh" }))
{
#Html.ValidationSummary();
#Html.TextBoxFor(modelitem => Model.Requirement)
}
How can I make that form submit to the controller method upon edit of the textbox? (if possible).
I think the jQuery solution this should work like this:
<script type="text/javascript">
$('#Requirement').change(function () {
$('#refresh').submit();
});
</script>
The above will run when the text box loses focus (and had changed value), if you want to do it on every keypress you can replace change for keyup or keydown as you see fit.
Related
I am using Hiddenvariable here and it is passed to controller from view.
#(Html.Search("ConfigurationSearch").Form("ConfigurationForm").Grid("gridConfiguration").ShowUnSelectAll(false))
<div id="gridConfiguration"></div>
</div>
#Html.Hidden("hidSearchText")
$(function () {
$('#searchText_ConfigurationSearch').val("#TempData["SearchText"]");
});
$('.k-block').click(function () {
$("#hidSearchText").val($("#searchText_ConfigurationSearch").val());
});
Without using hiddenvariable Can we Implement this,Please suggest me?!
The issue I am facing now is a button click event is automatically being fired when enter key is pressed in Html.TextBoxFor(). I am having a main view. In this view there are 3 buttons. On each of 2 button click a partial view is opened and during 3rd button click, a new view is opened. Please see the code below :
<script>
$(document).ready(function () {
SetUpDatePickers();
});
$('#button1').click(function (event) {
$('#divdefinetraj').toggle();
$('#button1').hide();
$('#button2').hide();
$('#button3').hide();
event.preventDefault();
GetTrajectories();
});
$('#button2').click(function (event) {
$('#divRequestTT').toggle();
$('#button1').hide();
$('#button2').hide();
$('#button3').hide();
event.preventDefault();
});
$('#button3').click(function (event) {
window.location.href = '/UserManagement/UsersList/';
event.preventDefault();
});
</script>
I clicked button1 and the first partial view is opened :
The partial view has below code :
#Html.TextBoxFor(u => u.TrajName, new { #class = "txtboxclass", #id = "TrajName" })
My issue is when I press "Enter" key inside this text box, the code for button1 in main view is being executed :
$('#button1').click(function (event) {
$('#divdefinetraj').toggle();
$('#button1').hide();
$('#button2').hide();
$('#button3').hide();
event.preventDefault();
GetTrajectories();
});
This results in all the buttons being hidden and the view becomes useless unless user reloads the view forcefully.
I tried to handle the onchange() event of the textboxfor and redirected to below function, but it doesn't handle.
function EnterKeyFilter() {
if (window.event.keyCode == 13) {
event.returnValue = false;
event.cancel = true;
}
}
Even I tried the same function for div - click() .. It doesn't work.
When I press the enter key the exact button1 click is being handled with this information event = j…y.Event {originalEvent: MouseEvent, type: "click", timeStamp: 7055.025000000001, jQuery110208686809991100928: true, toElement: button#button1.
But I am not clicking it either. The partial view is not part of a form also and form submission is not the issue. I am new to ASP.NET MVC and confused with this strange behavior. Please help. Thanks in advance.
If you want to disable your press enter in your keyboard, try this:
$(function () {
//On your document ready function, add this:
$('html').bind('keypress', function (e) {
if (e.keyCode == 13) {
return false;
}
});
}
Try to keep all three buttons in different form tags and made them submit button.
So in this case, whenever you hit enter in a form input, respective button will be clicked. To prevent full page postback, use e.preventDefault() in button click event.
HTML:
<form id="frm1">
-------------
-------------
<input id="btnSubmit" type="submit" value="submit" />
</form>
jQuery
$("#btnSubmit").click(function(e){
e.preventDefault();
-- rest of code
});
This is a follow on to similar question but taking suggestions into account.
Render part of page on dropdown selection
I have a chart on my main view which I would like to update partially when a dropdown selects different values.
The page renders correctly the first time, but when I select a new value in the dropdown, then I think the .submit script is failing in the script .submit() because when I put a break on window.submitAjaxForm it is never reached.
_PnlChart.cshtml
<img src="#Url.Action("CreateTraderPnlChart3")" width="600" height="600" align="middle" vspace="50" />
My mainview Index.cshtml:
<div class="w3-half">
<div id="ExportDiv">
#{ Html.RenderPartial("_PnlChart");}
</div>
#using (Ajax.BeginForm("GetEnvironment",
new RouteValueDictionary { { "Environment", "" } }, new AjaxOptions() { UpdateTargetId = "ExportDiv" }, new { id = "ajaxForm" } ))
{
#Html.DropDownList("PeriodSelection",
new SelectList((string[])Session["Periods"]),
(string)Session["Period"],
new
{ onchange = "submitAjaxForm()" })
}
</script>
<script type="text/javascript">
$('form#ajaxForm').submit(function(event) {
eval($(this).attr('onsubmit')); return false;
});
window.submitAjaxForm = function(){
$('form#ajaxForm').submit();
}
</script>
</div>
My controller:
public ActionResult PeriodSelection(string dropdownlistReturnValue) // dont know what dropdownlistReturnValue is doing?
{
Session["Period"] = dropdownlistReturnValue;
return PartialView("~/Views/Employee/_PnlChart.cshtml");
}
This line in your code,
eval($(this).attr('onsubmit')); return false;
I am not sure what you were intending to do here. But from your question, i assume you wanted to do a form submission. But that line will not submit the form. The expression $(this).attr('onsubmit') is going to return undefined as your form does not have an onsubmit attribute defined.
But you already have the form submit code in your other method (submitAjaxForm). So if you simply remove the $('form#ajaxForm').submit handler (apparently it does not do anything useful), your code will work. When you change the dropdown, it will make an ajax form submission.
But your form action is set to GetEnvironment action method. That means your ajax form submission will be to that action method. In your question you have a different action method which returns the updated chart content. It does not makes sense!
I personally prefer to write handwritten ajax calls instead of relying on the ajax action helper methods. The below is the code i would probably use (Except the dropdownlist code. read further)
<div id="ExportDiv">
#{ Html.RenderPartial("_PnlChart");}
</div>
#Html.DropDownList("PeriodSelection",
new SelectList((string[])Session["Periods"]),
(string)Session["Period"], new
{ data_charturl = Url.Action("PeriodSelection","Home")})
Now listen to the change event of the SELECT element.
$(function(){
$("#PeriodSelection").change(function(){
var v = $(this).val();
var url=$(this).data("charturl")+'?dropdownlistReturnValue='+v;
$("#ExportDiv").load(url);
});
});
You should consider using the a view model to pass the Dropdownlist data. Why not use the DropDownListFor helper method ? It looks much clean, Mixing a lot of C# code (See all the session casting and all.) makes it kind of dirty IMHO.
Let's say I have a view with Kendo treeview bounded to remote data source.
#(Html.Kendo().TreeView()
.Name("schemas")
.DataTextField("name")
.DataSource(dataSource => dataSource.Read(read => read.Action("Schemas", "Forms")))
.Events(events => events
.Select("onSelected")))
So the treeview just makes a call to the Schemas action in my FormsController
Also on the same page I have a form, which is simply the textbox and a button to submit the form
#using (Html.BeginForm("Load", "Forms", FormMethod.Post))
{
<div id="rootNode">
#Html.TextBox("rootElementName")
#Html.Button("next")
</div>
}
So I am just wondering what is the best way to handle user input and pass it to the the Load action of the FormsController? The user should select one of the options in the treeview and enter the value into textbox.
Or should I create some sort of viewmodel for my view with all my nodes inside + two additional fields for the textbox input and selected node?
I would take out the form elements, leaving:
<div id="rootNode">
#Html.TextBox("rootElementName")
#Html.Button("next")
</div>
The following js, this will pick up the tree item id on select.
The second function will call your Form controller action with the parameters.
<script>
var selectedNodeid;
//get the tree selected item id
function onSelected(e) {
var data = $('#schemas).data('kendoTreeView').dataItem(e.node);
selectedNodeid = data.id;
}
//button on click event
$(document).ready(function () {
$("#next")
.bind("click", function () {
//get parameters then pa
var id = selectedNodeid;
var rootElementName = $('#rootElementName).val()
$.ajax({
url: "Form/Load",
data:{id:id,rootElementName:rootElementName},
success: function () { }
});
}
})
</script>
I haven't tested this but it should be close.
I look forward to someone adding a better approach.
I'm trying to prevent the scrolling to the top when using jQuery's .load function. I've read at SO that you can use event.preventDefault(); event.stopPropagation();. Here is the link to this question. But when using beginform, you don't have an event here.
I also tried to put a click event on the submit button, but this also didn't work.
Thanks in advance!
This is the code of the view. When success the function closeFancyReservationCancel is called.
#using (
Ajax.BeginForm("Cancel",
"Reservation",
new AjaxOptions { HttpMethod = "POST",
OnSuccess = "closeFancyReservationCancel"},
new { id = "cancelForm" }))
{
...
}
)
And this is the jQuery function
function closeFancyReservationCancel() {
$.fancybox.close();
$('#reservationList').load(ResolveUrl('~/Reservation/reservationList'));
}
function ResolveUrl(url) {
if (url.indexOf("~/") == 0) {
url = baseUrl + url.substring(2);
}
return url;
}
Here a part of my HTML:
<div id="reservationList" class="tblContainer">
#Html.Action("reservationList", "Reservation")
</div>
The action reservationList returns a view with the table. Only the body of the table has an overflow: auto;.
EDIT: added more information
I have a div with a list of my reservations table. I am using MVC3 to show that list. When press the cancel button, the div will reload by the .load function.
EDIT
Here my HTML view with the table:
Pastebin
You can simply get the Scroll amount before loading. And apply the same scroll amount after load is finished
function closeFancyReservationCancel() {
$.fancybox.close();
var scroll_amount= $('#reservationList').scrollTop();
$('#reservationList').load(ResolveUrl('~/Reservation/reservationList'),
function() {
$('#reservationList').scrollTop(scroll_amount);
});
}
If you want you can also use .scrollLeft() amount.