ASP.NET MVC 3 Razor views onclick encoding - asp.net-mvc-3

I'm trying to get my checkbox to submit the form it is in using the below code:
#Html.CheckBox("Completed", new { onclick = "$(this).parent('form:first').submit();" })
It keeps rendering the ' around 'form:first' as html encode values though. Any ideas how to fix this?
Thanks
Nick

why not just wire it up with a jquery click event??
#Html.CheckBox("Completed", new { id = "myButtonID" })
then in your js code...
$(function(){
$("#myButtonID").click(function(){
//submit the form here
});
});

Related

MVC button click to action [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Mvc Html.ActionButton
With ASP.NET MVC 3 I know how to create a link to an action method very easily but what I'd like to know is how do you make a button (when clicked) call a particular action method?
Sachin,
If you're using jquery (which you don't mention but I'll show as it's fairly standard with mvc), you'd do the following:
$('#buttonId').click(function(){
document.location = '#Url.Action("MyAction","MyController")';
});
of course, you'd probably want to use ajax, but this is a basic example.
You could use an html <form>:
#using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Get))
{
<input type="submit" value="Click me" />
}
How do you do it?
The same way you would if not using MVC.
<INPUT TYPE="BUTTON" VALUE="Home Page" ONCLICK="window.location.href='/Controller/Action'">
As well as Darin's answer about using a form GET method, you can also call javascript functions that will then in turn call an action.
You can intercept the button click event when clicked and run your own code. That code can call an action asynchronously using Ajax or just simply navigate to an action method
Here's sample javascript that intercepts the button click event
$(document).ready(function () {
myButton.onclick = function (event) {
// in here you can call an ajax method or just navigate to an action
return false;
}
// or using jQuery
$('#myButton').click(function (e) {
// do whatever here
e.preventDefault;
});
});
Or you can intercept a button that has an href attribute
$(function () {
$("#myButton").click(function () {
var href = $(this).attr("href");
var route = href + "?paramName=" + $('#SomeValue').val();
$(this).attr("href", route);
});
});
This adds parameter information that you may have stored in another input on the page and appends it to the Url and then navigates to the action

Using Jquery in Controller Page-ASP.NET MVC-3

Could any one give an example, how to use Jquery in Controller Page. MVC3 -ASP.NET(How To put various tags like )
I want to show a simple alert before rendering a view in Controller.
Thank you.
Hari Gillala
Normally scripts are part of the views. Controllers shouldn't be tied to javascript. So inside a view you use the <script> tag where you put javascript. So for example if you wanted to show an alert just before rendering a view you could put the following in the <head> section of this view:
<script type="text/javascript">
alert('simple alert');
</script>
As far as jQuery is concerned, it usually is used to manipulate the DOM so you would wrap all DOM manipulation functions in a document.ready (unless you include this script tag at the end, just before closing the <body>):
<script type="text/javascript">
$(function() {
// ... put your jQuery code here
});
</script>
If you are talking about rendering partial views with AJAX that's another matter. You could have a link on some page that is pointing to a controller action:
#Html.ActionLink("click me", "someAction", null, new { id = "mylink" })
and a div container somewhere on the page:
<div id="result"></div>
Now you could unobtrusively AJAXify this link and inject the resulting HTML into the div:
$(function() {
$('#mylink').click(function() {
$('#result').load(this.href, function() {
alert('AJAX request finished => displaying results in the div');
});
return false;
});
});

Zend form ajax validation on submit

I am currently trying to validate a zend form with ajax and zend validate at the same time...
Let me explain, my forms pops up in an iframe (fancybox) and when submitted, I need to display a "thank you" message, close the iframe and redirect the user. I planned to use ajax validation to close the fancybox iframe if success.
I followed several tutorials http://www.zendcasts.com/ajaxify-your-zend_form-validation-with-jquery/2010/04/ explaining how to ajaxify your zend form to display errors for instance onblur event on a textinput.
Everything works find onblur or over events but when I specify the click event on the submit button, my guess is that the form gets processed by zend and ajax validation doesn't work... Do you have any hints or do you see obvious mistakes??
thanks a lot....
the javascript:
$(function()
{
$('#contact').submit(function()
{
doValidation();
});
});
function doValidation()
{
var url = '/ceramstar/public/contact/validateform';
var data = {};
$("input").each(function(){
data[$(this).attr('name')] = $(this).val();
});
$.post(url,data,function(resp)
{
//document.write(resp);
console.log(resp);
alert(resp);
//parent.$.fancybox.close();
},"json");
}
the zend action:
public function validateformAction()
{
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();
$form = new Form_ContactForm();
$form->isValidPartial($this->_getAllParams());
//print_r($bool);
$json = $form->processAjax($this->getRequest ()->getPost ());
header('Content-type: application/json');
echo Zend_Json::encode($json);
}
You should return false or preventDefault on the .submit
(function() {
$('#contact').submit(function() {
doValidation();
return false;
}
});

asp.net mvc 3 validation summary not showing via unobtrusive validation

I'm having problems getting the asp.net MVC client-side validation to work how I want it.
I have it basically working, however, the validation summary is not displayed until the user clicks the submit button, even though the individual inputs are being highlighted as invalid as the user tabs/clicks etc their way through the form. This is all happening client-side.
I would have thought the that the validation summary would be displayed as soon as an input field was discovered that was invalid.
Is this behaviour by design? Is there any way around it, as I would like the validation summary to be displayed as soon as it is discovered that one of the input fields is invalid.
My code is basically,
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
...
#using (Html.BeginForm())
{
#Html.ValidationSummary(false)
#Html.EditorFor(model => model);
...
And my _Layout.cshtml references jquery-1.4.4.min.js.
I used a version of Torbjörn Nomells answer
Except here I hang resetSummary off the validator object
$.validator.prototype.resetSummary= function () {
var form = $(this.currentForm);
form.find("[data-valmsg-summary=true]")
.removeClass("validation-summary-errors")
.addClass("validation-summary-valid")
.find("ul")
.empty();
return this;
};
Then change calling it to
$.validator.setDefaults({
showErrors: function (errorMap, errorList) {
this.defaultShowErrors();
this.checkForm();
if (this.errorList.length) {
$(this.currentForm).triggerHandler("invalid-form", [this]);
} else {
this.resetSummary();
}
}
});
You can setup the validation summary to be triggered a lot more often, in onready:
var validator = $('form').data('validator');
validator.settings.showErrors = function (map, errors) {
this.defaultShowErrors();
this.checkForm();
if (this.errorList.length)
$(this.currentForm).triggerHandler("invalid-form", [this]);
else
$(this.currentForm).resetSummary();
}
}
Here's the resetSummary used above:
jQuery.fn.resetSummary = function () {
var form = this.is('form') ? this : this.closest('form');
form.find("[data-valmsg-summary=true]")
.removeClass("validation-summary-errors")
.addClass("validation-summary-valid")
.find("ul")
.empty();
return this;
};
I have a similar question open here: How to display MVC 3 client side validation results in validation summary but the suggested solution by Darin does not seem to work the way I (and probably you) want it to.

jquery with boxy plugin - load and submit a form via ajax

I am using JQuery with Boxy plugin.
When a user clicks on a link on one page, I call Boxy.load to load a form onto the pop-up. The form loads and is displayed inside the pop-up without problems.
However, I can't bind the form to a submit event, since I can't select the form element.
This is the event handler:
$('#flag-link a.unflagged').click (function(e) {
url = $(e.target).attr('href');
Boxy.load(url, {behaviours: function(r) {
alert ($("#flag-form").attr('id'));
}
});
});
The alert reads "undefined" when it is displayed.
And this is the form:
<form id="flag-form" method="POST" action="somepage">
<table>
<tr><td><input type="text" name = "name"></td></tr>
<tr><td><input type="submit" value="OK"></td></tr>
</table>
</form>
What am I doing wrong?
First (a minor point, but a potential source of trouble), it should be id="flag-form" not id = "flag-form" (no spaces).
Second, you shouldn't need r.find(). Just do $("#flag-form").attr("id")
As far as I understand, live() method must be used to bind an element to an event in this case:
$("#flag-form").live("submit", function(){ ... }
Presently, live method is documented to be not supporting the submit event. However, I could work it out with Chrome and FF. On the other hand, I couldn't get it working in IE. A better way for cross-browser compatibility seems to be binding the submit button of the form to the click event.
$("#flag-form-submit").live("click", function(){
I learnt that declaring methods in behaviours: function (e) {} works, in addition to using live() methods.
E.g.:
$('#flag-link a.unflagged').click (function() {
Boxy.load(this.href, {
behaviours: function(r) {
r.find('#flag-form').bind('submit', function() {
// do on submit e.g. ajax calls etc.
});
}
});
return false;
});
Boxy opens the URL (url = $(e.target).attr('href');) in an iframe. So you cannot find the form from the opening page(parent page). Your code to bind the form should be in the child page (ie, the Boxy iframe). You can check the iframe URL using your code, url = $(e.target).attr('href');

Resources