Mvc3 validatios are not firing - asp.net-mvc-3

I am using Javascript serializer for passing model data to controller but this is not firing the code validation.
Here is the code
<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/microsoftajax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#btnCreateDepartment").click(function () {
var name = $('#txtDeptName').val();
$.ajax({
data: { modelName: 'DEPARTMENT', values: Sys.Serialization.JavaScriptSerializer.serialize(
{
DeptName: name
}
)
},
url: '#Url.Action("Create", "Office")',
type: "POST",
complete: function (result) {
debugger
alert("complete");
},
error: function (result) {
debugger
alert(result.statusText);
}
}); //Endof ajax
return false;
}); //end of click
}); // end of ready
</script>
In model the i have added validation as following
[Required(ErrorMessage = "Please Enter department")]
public string DeptName { get; set; }
But this is not getting fired .

Passing the object via ajax to the controller will disable the default mvc validation form. This validation will only work if you do a normal post.
Anyway if you want to use ajax you need to do the validation using jquery. If you decide not to use ajax then you can use mvc's built in validation. I also recommend fluent validation library for MVC

Change data parameter of your jQuery ajax to
data: { DeptName: name },
so it contains only properties of your model. Other department properties should follow DeptName ex. { DeptName: name, DeptAddress: address, ... }.
If your mvc model was mirrored on client side as a javascript model department you would just go:
data: { JSON.stringify(department) },

Related

Can't load data using Ajax for Razor Pages

I have this ajax call in my view, Form.cshtml
<form id="myForm">
<input id="btnSubmit" type="submit" value="Load data" />
<p id="result"></p>
</form>
#section scripts{
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
debugger
$.get('/Form/',function (data) {
debugger
console.log('test');
});
})
});
</script>
}
and in my Razor Pages code behind, Form.cshtml.cs
public class FormModel : PageModel
{
public JsonResult OnPost()
{
List<Student> students = new List<Student>{
new Student { Id = 1, Name = "John"},
new Student { Id = 2, Name = "Mike"}
};
return new JsonResult(students);
}
}
The problem is it doesn't reach OnPost method. If I put in OnGet, it will automatically load before I click the Submit button.
I try to create another Razor page called Filter.cshtml and in Filter.cshtml.cs. And then in my Form.cshtml, I changed my url to /Filter/, it did reach OnGet in Filter.cshtml.cs
public class FilterModel : PageModel
{
public JsonResult OnGet()
{
List<Student> students = new List<Student>{
new Student { Id = 1, Name = "John"},
new Student { Id = 2, Name = "Mike"}
};
return new JsonResult(students);
}
}
The default behaviour of clicking a submit button in a form is that the form gets submitted. At the moment, your form has no method specified, so the submission will default to the GET method. If you want to submit the form by AJAX POST rather than the usual behaviour, you need to do two things:
Cancel the default action of the button click (which is what currently causes the OnGet handler to execute)
Change the jQuery code to use the POST method:
#section scripts{
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function (e) { // include the event parameter
e.preventDefault(); // prevents the default submission of the form
$.post('/Form/',function (data) { // change from 'get' to 'post'
console.log('test');
});
});
});
</script>
}
the $.get() makes Ajax requests using the HTTP GET method, whereas the $.post() makes Ajax requests using the HTTP POST method.
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/Filter/OnGet",
success: function (result) {
}
});

Angular ng-grid issue

I am trying to use ng-grid using the following tutorial.
http://angular-ui.github.io/ng-grid/
Here is my View
<script type="text/javascript" src="#Url.Content("~/Scripts/jquery-1.8.2.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/angular.js")"></script>
<script type="text/javascript" src="#Url.Content("~/Scripts/angular-resource.js")"></script>
#*<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.min.js"></script>*#
<script type="text/javascript" src="#Url.Content("~/Scripts/ng-grid-2.0.7.min.js")"></script>
<script src="~/Scripts/PostsController.js"></script>
<script src="~/Scripts/postreq.js"></script>
<link rel="stylesheet" type="text/css" href="~/Content/ng-grid.min.css" />
<div data-ng-controller="PostsController">
<div class="gridStyle" data-ng-grid="gridOptions"></div>
</div>
Here is my Angular code
function PostsController($scope, $http) {
$http({ method: 'GET', url: '/api/request' }).
success(function (data, status, headers, config) {
$scope.posts = data;
}).
error(function (data, status, headers, config) {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
$scope.gridOptions = { data: 'posts' };
}
However, when i run the application i see blank square in browser and there is no error showing in the console.
Please help me to fix this issue.
FYI: I checked API response directly in browser and it shows with data.
It seems to me that you are missing some steps of the tutorial you are following :
Where you declare your app module, add ngGrid:
angular.module('myApp',['ngGrid']);
I do not see your module declaration anywhere.
Do you have ng-app="myApp" defined at the top of your page?
I also noticed that you do not have a css class defined for "gridStyle". "gridStyle" is not part of the ng-grid css.
Sounds odd, but this worked for me by using a timeout. Try it like this:
setTimeout(function () {
$http.get('/api/request')
.success(function (data, status) {
$scope.posts = data;
})
.error(function (data, status) {
alert(status);
});
}, 100);

submitting an asp.net MVC 3 form using jquery ajax

I am working on ASP.NET MVC 3 application and I have a jquery dialogue with Ok button. On click of OK I want to submit a form using jquery AJAX.
My ajax call looks like this:
$("#free-trial").dialog({
autoOpen: false,
autoResize: true,
buttons: {
"OK": function () {
if (notvalid()) {
$(".ui-dialog-titlebar").hide();
$("#dialog-freetrial-insufficientdata").dialog({ dialogClass: 'transparent' });
$("#dialog-freetrial-insufficientdata").dialog("open");
}
else {
$('#frmCreateTrialAccount').live('submit', function (e) {
e.preventDefault();
$.ajax({
cache: false,
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
success: function (data) {
alert(data);
}
});
});
jQuery(this).dialog('close');
}
}
},
open: function () {
$('.ui-dialog-buttonset').find('button:contains("OK")').focus();
$('.ui-dialog-buttonset').find('button:contains("OK")').addClass('customokbutton');
}
});
where as form looks like this:
#using (Html.BeginForm("CreateTrialAccount", "Home", FormMethod.Post,
new { Id = "frmCreateTrialAccount" } ))
{
}
and controller action looks like this:
[HttpPost]
public JsonResult CreateTrialAccount(FormCollection form) {
return Json("dummy data");
}
but form is not submitted on this method.
I have these files included in layout page:
<link href="#Url.Content("~/Content/css/smoothness/jquery-ui-1.10.0.custom.css")" rel="stylesheet" type="text/css" media="screen"/>
<script src="#Url.Content("~/Scripts/jquery-1.9.1.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.10.2.custom.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
Please suggest me solution to this.
Oh sorry for that comment I made, your issue is that you are binding the form's submit action where you should have been submitting it already. If you want to bind the form's submit then declare it outside $("#free-trial").dialog({. Then you can have the ajax post method in a separate function so you can call it in both the binding code and in the $("#free-trial").dialog({.
var form = $('#frmCreateTrialAccount');
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert(data);
}
});
So just to make it clear remove the following lines of code:
$('#frmCreateTrialAccount').live('submit', function (e) {
e.preventDefault();
// and the ending
});

Prototype AJAX Updater Multiple Requests

I am just beginning to learn AJAX and am trying to build a cascading dropdown that pulls information from a database. My AJAX.Updater code works, but not only for one of the dropdowns. How do I make multiple AJAX.Updater calls?
<script type="text/javascript" src="jQuery/jquery-latest.js"></script>
<script type="text/javascript" src="jQuery/prototypejs.js"></script>
<script language="javascript">
jQuery(document).ready(function()
{
jQuery('#regiondropdown').change(function() {
dropdowns(jQuery(this).val(),"foo");
});
jQuery('#foodropdown').change(function() {
dropdowns(jQuery(this).val(),"bar");
});
}
);
function dropdowns(str,type)
{
if (type=="foo") {
new Ajax.Updater('foo', 'foo_dropdown.php', { method: 'get', parameters: {foo: str} });
} else if (type=="bar") {
new Ajax.Updater('bar', 'bar_dropdown.php', { method: 'get', parameters: {bar: str} });
}
}
</script>
I can't see what it is so I suggest you fire up your debugger.
1) Check the value of jQuery(this).val() for both cases. "this" might not be what you believe in Javascript.
2) Check what happens if you switch the if.. and else... in dropdowns. Maybe there is a (, { or ; out of place.
HTH

No result-message from JsonResult method

I went through the suggested related topics before asking this question but none of them could solve my problem. So in advance, sorry for a possible dubplicate..
In my ASP.NET MVC3 application I have following function that is attached to a button:
save: function () {
$.ajax({
url: "#Url.Action("Save")",
type: "post",
data: ko.toJSON(this),
contentType: "application/json",
succes: function (result) { alert(result.message) },
});
}
In my Controller I have a JsonResult-method like this:
public JsonResult Save(Person person)
{
//process person-parameter and send message back
var message = "Dummy result-message";
return Json(new { message });
}
And these are the JavaScript - files I have referenced:
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.tmpl.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/knockout-1.2.1.js")" type="text/javascript"></script>
I debugged the application using breakpoints and the button - event is fired like it should and the method in the Controller is called. The processing of the Person-parameter is done and I call the return - statment. But the problem is: I don't get an alert...
For a couple of hours now I've been looking on the internet on how to solve this but I can't seem to find the solution. I hope any of you guys can get me back on the right track. Thanks in advance!
success setting is misspelled :)

Resources