MVC3 client validation: how to prevent page reloading? - asp.net-mvc-3

I have page with form:
#using (Html.BeginForm("Create", "Theme", FormMethod.Post, new { id = "frm_post", enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
#Html.TextBoxFor(model => model.Name)
#Html.ValidationMessageFor(m => m.Name)
<input type="image" src="img.png"
onclick="javascript:if(func()){document.getElementById('frm_post').submit();}else{return false;}"/>
}
I included scripts to page:
<script src="#Url.Content("~/Scripts/jquery-1.5.2.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
I have such strings in web.config:
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
I have [Required] for Name in Model.
But when I left textbox Name empty and submit form, error message is shown for some seconds and then page reload. How can I stop reloading of page?

O-o-ops... I just should remove form.submit() from onclick event of my button.
So, if I use
<input type="image" src="img.png"
onclick="javascript:if(!func()){return false;}"/>
it works fine.

It looks like you might want to remove that inline onclick handler and consider writing instead a custom validator. This http://blogs.msdn.com/b/stuartleeks/archive/2011/01/25/asp-net-mvc-3-integrating-with-the-jquery-ui-date-picker-and-adding-a-jquery-validate-date-range-validator.aspx is a good example of how to write one in MVC3 using unobtrusive validation. It's for a custom datepicker but the same principle can be applied for your custom validation.

Related

POST an Ajax form from a Kendo UI window

To edit a record, I'm opening a modal Kendo UI window populated with a partial view containing an AJAX enabled form:
#model MVC_ACME_Hardware.Models.BaseModel
<script type="text/javascript">
$(function () {
$("form").kendoValidator();
});
</script>
#using (Ajax.BeginForm("EditProduct", new AjaxOptions { UpdateTargetId = "ProductDiv", OnSuccess = "SomeMethod" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>EmployeeFTE</legend>
#Html.HiddenFor(model => model.Products.Product_ID)
<div class="editor-label">
#Html.LabelFor(model => model.Products.Product_Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Products.Product_Name)
#Html.ValidationMessageFor(model => model.Products.Product_Name)
</div>
<input type="submit" value="Save" class="myButton" />
</fieldset>
}
When I run the form and click 'Save' on the popup, the form posts successfully but the post is not done via AJAX and my 'SomeMethod' onsuccess method is not being called. I've tried adding...
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
...on the partial view but it did not help. How can I get my form to submit using AJAX? I'm missing something obvious. Thanks!
try something like this (attention to the input type):
<input type="button" value="Save" class="myButton" id="btnSave" />
and the in the $(document).ready() :
var validator = $(document.forms[0]).kendoValidator().data("kendoValidator");
$("#btnSave").click(function(e) {
if (validator.validate()) {
var formContent = $(document.forms[0]).serialize();
var url = $(document.forms[0]).action;
$.post(url, formContent).done(function(data) {
$(document.body).append("<div class='savedRecordMessage'>success</div>");
});
}
});
I think you need to add these files if you want to use unobtrusive validation of MVC and Ajax options of AJAX form.
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

#Ajax.Actionlink render partialview

I am trying to use Ajax.Actionlink to render a partial view. But it only redirects me to the partial view. I also added: <add key="UnobtrusiveJavaScriptEnabled" value="true" /> to webconfig. Anyone?
My layout.cshtml Scripts.render and script is in head tag. Ajax.actionlink and div is in body
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/Scripts/jqueries")
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
#Ajax.ActionLink("Ajax Click", "Document","Home", new AjaxOptions { UpdateTargetId = "result", InsertionMode = InsertionMode.Replace })
<div id="result">
</div>
Home controller:
public PartialViewResult Document()
{
return PartialView("Document", om);
}
My Document.cshtml
#model mymodel
#foreach (var item in Model)
{
<li>#Html.ActionLink(item.something, "Controller", "Action")</li>
}
Your jquery and unobtrusive-ajax should be at the bottom of the page, like this
</footer>
#Scripts.Render("~/bundles/jquery")
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
#RenderSection("scripts", required: false)
</body>
</html>
Information why can be found here
http://developer.yahoo.com/performance/rules.html/
Placing this at the wrong place, WILL result in errors

asp.net mvc 3 ajax form with in telrik Grid On Submits Opens a New Page

in my ASP. Net MVC 3.0 Project.
I have Telerik Grid.
with in the grid cell I am loading content from partial view with a Ajax Form in it.
(for each Cell in one column of the grid)
when i submit that form.
Ajax form is opening new page instead of updating the target ID.
I am loading the required scripts
<script src="#Url.Content("~/Scripts/jquery-1.6.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
These scripts are loaded on master page (_Layout.cshtml)
My Web.config
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
I have used the Ajax forms at most of the places in this project.
It works perfect at all those places.
Any clue if i can submit ajax form from a telerik grid
More Details
Controller
public JsonResult AddRemoveThisLocation(int LocationID, FormCollection collection, string button)
{
return Json(new
{
success = _success,
message = _message
}, JsonRequestBehavior.AllowGet);
}
}
Partial View loaded in to the Telerik Grid using .loadContentfrom() method
#using(Ajax.BeginForm("AddRemoveThisLocation", "Controller", new { LocationID = Model.AddressID }, new AjaxOptions {
OnBegin="ValidateNumbers",
HttpMethod = "POST",
OnSuccess = "ShowSignUpStatus"} ))
{
#Html.TextBoxFor(model => model.Phone, new { id="phone"+Model.AddressID, name="Phone" })
<input type="submit" value="Add" class="button" name="button" id="#(Model.AddressID)" />
}
I had similar problem. adn the solution is confirm no repeated jQuery References
and check if these are loadin correctly.
<script src="#Url.Content("~/Scripts/jquery-1.6.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
That should fix your problem.
Try this:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult AddRemoveThisLocation(int LocationID, FormCollection collection, string button)
{
return Json(new
{
success = _success,
message = _message
}, JsonRequestBehavior.AllowGet);
}
}

Transform MVC3 (Razor) form to Ajax form

I have an MVC3 Razor form in index.cshtml using HtmlHelper. It works, but I want to replace it with Ajax form using AjaxHelper (note: I am still not familiar to Ajax/jQuery). It fails. My questions:
What's wrong with my code?
Are there any good websites that explain this kind of transformation?
If one transforms a view to Ajax processing, is it necessary to change the controller as well?
Here's my index.cshtml file. My trial with Ajax is commented out below the MVC3 form.
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>
#using ( Html.BeginForm("UploadFile", "Home", FormMethod.Post, new
{
enctype = "multipart/form-data"
}) )
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Select a file</legend>
<input type="file" id="fileupload" name="fileuploadname" />
<p>
<input type="submit" value="Upload" id="upload" onclick="javascript:document.getElementById('upload').disabled=true; document.getElementById('upload').value='Uploading...'" />
</p>
</fieldset>
}
#* #using ( Ajax.BeginForm("UploadFile", "Home",
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST"
}) )
{
<input type="file" id="fileupload" name="fileuploadname" />
<p>
<input type="submit" value="Upload" id="upload" onclick="javascript:document.getElementById('upload').disabled=true; document.getElementById('upload').value='Uploading...'" />
</p>
}
*#
Thx in advance.
You can't upload files using Ajax. At least not directly.
There are of course few plugins that help you with this, but they qork outside of AjaxHelper scope. This simply means you will have to get your hands dirty with jQuery which is also a good thing. It's a simple and small library and while getting acquainted with it you'll most likely deviate away from AjaxHelper and rather just use jQuery (with HtmlHelper).

Asp.Net MVC EnableClientValidation doesn't work

I want as well as Client Side Validation as Server Side Validation. I realized this as the following:
Model: ( The model has a DataModel(dbml) which contains the Test class )
namespace MyProject.TestProject
{
[MetadataType(typeof(TestMetaData))]
public partial class Test
{
}
public class TestMetaData
{
[Required(ErrorMessage="Please enter a name.")]
[StringLength(50)]
public string Name { get; set; }
}
}
Controller is nothing special.
The View:
<% Html.EnableClientValidation(); %>
<% using (Ajax.BeginForm("Index", "Test", FormMethod.Post,
new AjaxOptions {}, new { enctype = "multipart/form-data" }))
{%>
<%= Html.AntiForgeryToken()%>
<fieldset>
<legend>Widget Omschrijving</legend>
<div>
<%= Html.LabelFor(Model => Model.Name) %>
<%= Html.TextBoxFor(Model => Model.Name) %>
<%= Html.ValidationMessageFor(Model => Model.Name) %>
</div>
</fieldset>
<div>
<input type="submit" value="Save" />
</div>
<% } %>
To make this all work I added also references to js files:
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
Eventually it has to work, but it doesnt work 100%:
It does validates with no page refresh after pressing the button.
It also does "half" Client Side Validation. Only when you type some text into the textbox and then backspace the typed text. The Client Side Validation appears. But when I try this by tapping between controls there's no Client Side Validation.
Do I miss some reference or something? (I use Asp.Net MVC 2 RTM)
Change the order of the loaded javascript...
<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
Had the exact same problem and this cleared it up for me...
I thought I was missing something too, but I do know that the jQuery validation plug in doesn't react to mouseEnter/mouseLeave. According to the documentation for that plug in (at the plug in page - look for the section labeled "A few things to look for when playing around with the demo"):
Before a field is marked as invalid, the validation is lazy: Before submitting the form for the first time, the user can tab through fields without getting annoying messages - he won't get bugged before he had the chance to actually enter a correct value
I assume it's the same rule with MVC 2 client-side validation. I can't be sure of that because the documentation doesn't say anything but "it works on my machine" :).
I went with the jQuery validation route, which is supported in MVC Futures (note that the documentation for that is non-existent). To use it, you just need to replace the script tags for MicrosoftAjax.js, MicrosoftMvcAjax.js and MicrosoftMvcValidation.js files with these two tags:
<script src="/js/jquery.validate.js" type="text/javascript"></script>
<script src="/js/MicrosoftMvcJQueryValidation.js" type="text/javascript"></script>
replacing the path with yours.
I also found the need to upgrade to the latest version of jquery.validate.js from the developer's page, because we are using a later version of jQuery (1.4) here.
Hope that helps.
hm..., it's late to answer but try this:
<script src="<%= Url.Content("ScriptFile.js") %>" type="text/javascript"></script>

Resources