unobtrusive ajax form prevent cancel button from posting - asp.net-mvc-4

Question: Why is cancel button posting to the controller like submit?
I have the form below loaded from a partial view. Submit works fine. The only thing I've been struggling with is why Cancel doesn't just dismiss the form. I've tried a variety of things like capturing the click event. I looked at http://jimmylarkin.net/post/2012/05/16/Broken-Validation-on-Cancel-Buttons-With-Unobtrusive-Validation-Ajax.aspx as a possible solution but I'm not sure this is the problem it's intended to address. No doubt it's some ignorance on my part. So what bonehead thing am I missing?
//click event loading the form.
<script>
$(document).ready(function () {
$('#editbtn').click(function () {
var url = "/Quiz/EditQuiz?id=#id";
$.get(url, function (data) {
$('#formdiv').html(data);
$("#formdiv").show();
});
});
</script>
//form inside partial view.
#using (Ajax.BeginForm("EditQuiz", "Quiz", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "formdiv"
}))
{
#Html.ValidationSummary(true)
#Html.AntiForgeryToken()
<div>
<fieldset>
.
.
<input type="submit" class = "btn btn-primary" value="Save" />
<button class = "cancel" >Cancel </button>
</fieldset>
</div>
}

I'm curious if your cancel button is whats causing the submit by default. Try replacing your <button class="cancel"> with an Html helper. How about #Html.ActionLink("Cancel", "Index"). This is a link that has text Cancel and redirects to action Index.

Related

knockout model - observable empty in IE 11

I have a set of input fields that are used to set search params, passed to the controller via knockout and ajax upon pressing the 'search' button.
Each input is bound to a property in a viewModel - each one is a ko.observable().
I have code bound to the keyup event for these fields that will invoke the same search operation when the return key is pressed.
In Chrome, this works fine, but in IE(11) this is never passed!
I have also noted that if I press the tab key to go to the next field, and THEN press return, the search parameter I expect is now populated.
Any ideas? at my wits end...
How do I do the same as pressing the tab key in code, without pressing the tab key?
I think IE's handling of the .change() event in jquery might be different to everyone else...
edited to include sample code - js:
var searchVm = function () {
var self = this;
self.reference = ko.observable("");
self.postCode = ko.observable("");
self.description = ko.observable("");
self.doSearch = function () {
var date = {
Ref: self.reference(),
PostCode: self.postCode(),
Desc: self.description()
};
// do the ajax call to controller
// ... etc ...
}
}
$('.searchField').keyup(function(e) {
if (e.which===13) {
$('#btnSearch').click();
}
});
the page:
<div class='indexRow'>
<label>Reference:</label>
<input type='text' class='searchField' data-bind="value: reference" />
</div>
<div class='indexRow'>
<label>PostCode:</label>
<input type='text' class='searchField' data-bind="value: postCode" />
</div>
<div class='indexRow'>
<label>Description:</label>
<input type='text' class='searchField' data-bind="value: description" />
</div>
<button data-bind='click: doSearch'>Search</button>

How to use buttons in MVC for different purposes

I do have three buttons in my view. So now I want two buttons to post back and the third button to perform some jquery. How to do this. Like how to make the third button not to post back and perform some jquery actions.
Thanks
You can do this like
<form id="myForm">
<%-- form data inputs here ---%>
<button id="Postback">Postback</button>
<button id="JavaScript">JavaScript</button>
</form>
and in javascript
<script type="text/javascript">
$("#Postback").click(function() {
var form = $("form#myForm");
form.attr("action", "#Url.Action("action","MyController")");
form.submit();
});
$("#JavaScript").click(function() {
Do your javascript something.
});
</script>
In HTML the tag button has the attibute type:
To post back data (submit a form) you must set type to submit (this is default value, so you may drop the type attribute at all).
To perform some javascript actions you must set type to button.
In two different submit buttoms use same name and different values:
#using (Html.BeginForm("Login", "Home")
{
<label for="login">Login:</label>
#Html.TextBox("login", Model.Login)
<label for="password">Password:</label>
#Html.Password("password", "")
<button type="submit" name="what" value="login">Log in</button>
<button type="submit" name="what" value="register">Register</button>
<button type="button" id="facebook">Facebook authentication</button>
}
<script>
$(function() {
// Perform jquery action.
$('#facebook').click(...);
});
</script>
In controller:
public ActionResult Login(string login, string password, string what)
{
if (what == "login")
. . .
else if (what == "register")
return RedirectToAction("Register", "Home");
}

Pass Value of Drop Down as a Route Value to an Ajax Form

I am working on an ASP.NET MVC4 application, and I have the following in one of my views:
#using (Ajax.BeginForm("GetAllOrangeChocs", "ChocFactory", new { area = "Provider", Id = Model.FruitId }, new AjaxOptions { HttpMethod = "post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "ChocFruitWrap" }, null))
{
<div class="form-horizontal" role="form">
<div class="form-group">
<span class="col-md-2 control-label"><strong>Fruit Group:</strong></span>
<div class="col-md-3">
#Html.DropDownListFor(m => m.FruitlId, new SelectList(Model.ListOf_Fruits,"Id", "PortalDisplayName"),"--Please Select--")
</div>
<div class="btn-group col-md-1">
<button type="submit" class="btn btn-primary btn-sm">Submit</button>
</div>
</div>
</div>
}
So it is an Ajax form that calls some controller action that returns a PartialView to display on the page. The controller code is:
public PartialViewResult GetAllOrangeChocs(int Id)
{
var model = _service.GetMeSomethingUsefulWithPassedParam(Id);
return PartialView("_Categories", model);
}
My controller action is being hit, but the Id is always null, my guess is, it is because there is no two way binding in place! As the ViewModel is passed in the GET Request, the FruitId on the ViewModel is null, and it only actually gets set in the POST
Am I right in my reasoning? And if yes ... how can I easily pass the Value (the Id) of the selected item in the Drop Down list?
I know I can added a hidden field, and via jQuery populate it each time the drop down changes, but is there no cleaner way?
from the link you have an ajax call
$.ajax({
type: "POST",
url: '#Url.Action("GetAllOrangeChocs", "ChocFactory")',
data: {
Selected: $('#FruitlId').val()
}
success: function (result) {
$('.divContent').html(result);
}
});
through the data attribute you can send whatever you want. What I have here will put the selected value into a variable called Selector (make sure whatever you call it on the view matches exactly with the input parameter on the controller). Let me know if you have any questions.

Load link src into iFrame from an asp.net MVC4 controllers action method

created a MVC4 ASP.NET application with razor view
--view code here - iframe and the form with 2 fields on it. Enter ID and click the Search button does invokes the Index Action of the HomeController
#model BusinessApp.Models.SearchViewModel
<iframe id="photomural" name ="mural" src="http://www.mywebfind.com/search" scrolling="yes" width ="75%"> </iframe>
#using (Html.BeginForm("Index", "Home", FormMethod.Get)) {
#Html.ValidationSummary(false)
<fieldset>
<legend>Contact Search </legend>
<div>
#Html.LabelFor(model => model.SomeID)
</div>
<div >
#Html.EditorFor(model => model.SomeID)
#Html.ValidationMessageFor(model => model.SomeID)
</div>
<p>
<input name="SearchButton" type="submit" value="Search" />
</p>
</fieldset>
}
-- based on the user values entered in the search box - the Index action of the home controller is executed.
-- based on some logic that is then executed in the action I would like to have the "src" of the Iframe to be loaded with the link to some website
--CODE in action Method of Home Controller to change the "src" of the IFrame. Could someone please give me some pointers.
public class HomeController : Controller
{
public ActionResult Index(SearchViewModel searchVM)
{
if (searchVM.SomeID != null)
{
//Execute some logic to determine the ID of the URL below that will be passed to Iframe
}
???? Code to change the IFrame src to some url like
"http://OrderManagementSystem/ShowOrder.aspx?ID=10248" based on above logic
return ???
}
}
I appreciate any help I can get from any of the experts out there.
I had the same issue and couldn't find an answer anywhere. Then realized I could set the target in the #using statement to the id of your iframe and return your normal view. Hope this helps someone!
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { target = "photomural"} ))

Simple MVC4 unobtrusive ajax not working

I am writing a very simple MVC4 test page and unobtrusive Ajax does not seem to be working. When I click my submit Button the page is not submitted.
I have a breakpoint is VS and can tell there is no request.
I am using Firefox and when I click the submit button the Web Console shows this JavaScript error:
--- Empty string passed to getElementById()
Which occurs at line 16 in.--- jquery.unobtrusive-ajax.js
I setup ajax Options as follows:
AjaxOptions ajaxOpts = new AjaxOptions { UpdateTargetId = "officeList", Confirm = "Are you sure?", Url = Url.Action("GetOfficeData") };
Here is my AjaxForm:
#using (Ajax.BeginForm("GetOfficeData", ajaxOpts))
{
<div>
#Html.DropDownList("orgList", new SelectList(Model.Organizations, "ORGID", "ORGNAME"));
<button type="submit" id="btnSubmit">Submit</button>
</div>
}
I do get the 'Are you sure prompt' when I click the submit button (as defined in the ajax options).
If I change Ajax.BeginForm to:
#using (Html.BeginForm())
...
Then there is a request, my breakpoints get hit, and there as no JS errors.
I have used NuGet to get the latest version of both jQuery and unobtrusive-ajax. Here are
my script tags from view source (all of them – in order):
<script src="/Scripts/jquery-2.0.3.js"></script>
<script src="/Scripts/DataTables-1.9.4/media/js/jquery.dataTables.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="/Scripts/modernizr-2.5.3.js"></script>
Here is the form that gets rendered:
<form action="/Selectee/GetOfficeData" data-ajax="true" data-ajax-confirm="Are you sure?" data-ajax-mode="replace" data-ajax-update="#officeList" data-ajax-url="/Selectee/GetOfficeData" id="form0" method="post">
<div>
/*--my drop down .....
<br />
<button type="submit" id="btnSubmit">Submit</button>
</div>
</form>
Any ideas?
I have it working.
I did not have an Html.BeginForm(), only the Ajax.BeginForm(). Is that valid?
I added an Html.BeginForm() with an Ajax.BeginForm() and all my controls inside that form and it started working.
I thought Ajax.BeginForm() took the place of Html.BeginForm, but it appears I need both. Is that correct?