Validate Model data before ajax method call - c#

I have a partial view on my application I am creating user registration functionality on partial view(not using any form tag) , I am calling Controller's action method using ajax-jquery & passing user details(model) to action method , before calling ajax method i need to validate user detail at client side. how can i do this?
need to validate model before ajax call(not using any form tag).
#model MVC4Demo.Models.Student
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
function onClientClick() {
var obj = { FirstName: "name", City: "abc" };
$.ajax({
url: "/Home/AjaxDemo",
data: JSON.stringify(obj),
type: "POST",
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
alert('success');
},
error: function () {
alert("error");
}
});
}
</script>
<div id="Main">
<label>Student</label>
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.City)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.City)
#Html.ValidationMessageFor(model => model.City)
</div>
<p>
<input type="submit" onclick="onClientClick()" value="Create" />
</p>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>

Put your model into form. After:
<script>
$(function () {
$('#myForm').unbind('submit');
$('#myForm')
.bind('submit', function () {
var form = this;
if ($("#myForm").valid()) {
$.post('/Home/AjaxDemo', $(form).serialize(), function (data) {
if (data.success) {
alert('success');
} else {
alert("error");
}
});
}
return false;
});
});

I'm afraid a form tag is required. And something else, you can prepend
#Html.EnableClientValidation();
#Html.ValidationSummary(true);
to the form.

Related

There's some problem in "mixing ways" to do posts requests?

For example, in my project I'm using #using(Html.BeginForm(some stuff))to create an instance of my model and finally appending it to my database. But, when I'm editing (updating) some object of model, I'm usingn ajax get to retrieve data and finally using #Html.BeginForm() to post the update. Well, this is breaking some pattern of coding in MVC or whatever good principle?
Retrieving data and filling in the input fields
$.ajax({
url: "../../Obra/" + id,
type: "POST",
success: function(data) {
var obj = JSON.parse(JSON.stringify(data));
tit.value = obj.titulo;
ed.value = obj.editora;
obj.autores.forEach(x => {
var newn = divAutor.appendChild(aut.cloneNode());
newn.value = x;
});
img.value = obj.imagem;
divAutor.removeChild(aut);
},
error: function() {
alert('Error.');
}
});
All modal:
<div class="modal" id="modalOverlay">
<div class="modal-content" id="modalContent">
<header class="modal-header">
<h1 id="updateObraModalTitulo"></h1>
</header>
#using(#Html.BeginForm("Update", "Obra", FormMethod.Post, new { id="form-update" })) {
<div class="updateObraDivProp">
#Html.LabelFor(m => m.Titulo, "Título:")
#Html.TextBoxFor(m => m.Titulo, new { #class="editInputValue", #id="editTituloInput" })
</div>
<div class="updateObraDivProp">
#Html.LabelFor(m => m.Editora, "Editora:")
#Html.TextBoxFor(m => m.Editora, new { #class="editInputValue", #id="editEditoraInput"})
</div>
<div class="updateObraDivProp">
#Html.LabelFor(m => m.Autores, "Autores:")
<div id="divInputAutores">
#Html.TextBoxFor(m => m.Autores, new { #class="inputPostValue", id="addAutoresInput"})
</div>
<div class="btnNewAutorOp">
<button type="button" id="btnAddAutor" onclick="addNewAutor()">+</button>
<button type="button" id="btnDeleteAutor" onclick="deleteNewAutor()">×</button>
</div>
</div>
<div class="updateObraDivProp">
#Html.LabelFor(m => m.Imagem, "Imagem:")
#Html.TextBoxFor(m => m.Imagem, new { #class="inputPostValue", #id="editImagemInput" })
</div>
<input type="submit">
}
</div>
</div>
Because I can't retrieve the Id property when I click in the modal with mvc (or maybe I can using partial views?), I'm using javascript to create a function with the param id and getting data with ajax and finally updating with form

Passing and handling of varibles to a function with AJAX in MVC

I'm having trouble passing a variable into a function in my view. I'm fairly new to MVC and not sure how I save and pass information.
#model Models.Schedule.SheduleModel
#{
Layout = null;
}
<div>
<div class="tableRow">
<p>Make a schedule reminder.</p>
</div>
<div class="tableRow tableRowHeading">
<div class="row" style="width: 210px">Name</div>
<div class="row" style="width: 210px">Number</div>
</div>
#foreach (var shedule in Model.ScheduleList)
{
<div class="tableRow">
#using (Html.BeginForm("UpdateSchedule", "Schedule", FormMethod.Post))
{
<div class="cell" style="width: 210px">
#Html.HiddenFor(model => schedule.Id)
#Html.TextBoxFor(model => schedule.Name, new { #class = "inputFieldText" })
#Html.ValidationMessageFor(model => schedule.Name)
</div>
<div class="cell" style="width: 210px">
#Html.TextBoxFor(model => agent.ContactNumber, new { #class = "inputFieldText" })
#Html.ValidationMessageFor(model => agent.ContactNumber)
</div>
<div class="cell">
<button name="Update" type="submit" value="Update" class="button" title="Update details">
<span class="text">Update</span>
</button>
</div>
<div class="cell">
<button class="button" type="button" onclick="deleteFromSchedule();" value="Delete">
<span class="text">Delete</span>
</button>
</div>
}
</div>
}
</div>
#Scripts.Render("~/bundles/jqueryval")
<script>
function deleteFromSchedule() {
$.ajax(
{
type: 'POST',
url: urlBase + 'Schedule/UpdateSchedule/' + Id,
data:
{
Id: Id
},
success: function (data) {
console.log(data);
},
error: function () {
var errorMessage = 'Error occurred while sending message';
console.log(errorMessage);
}
});
}
}
</script>
I'm trying to pass the schedule Id in HiddenFor into the delete function but everything I try doesn't work, i'm also curious on how to handle the information gotten from the text box in a later unwritten div, I'd like to produce text on the screen saying
User #Model.Name and number #Model.Number will be notified of schedule change but I keep displaying blank spaces. an I use the form I'm creating for this information, what would the syntax be?. My method in the schedule controller is very straight forward.
[HttpPost]
public void UpdateSchedule(int Id)
{
////do stuff here
}
The simplest way is to add your id from the schedule into the inline function call (using razor), and add an id param into your javascript delete function:
<div class="cell">
<button class="button" type="button" onclick="deleteFromSchedule(#schedule.Id);" value="Delete">
<span class="text">Delete</span>
</button>
</div>
<script>
function deleteFromSchedule(id) {
$.ajax(
{
type: 'POST',
url: urlBase + 'Schedule/UpdateSchedule/' + id,
data:
{
Id: id
},
success: function (data) {
console.log(data);
},
error: function () {
var errorMessage = 'Error occurred while sending message';
console.log(errorMessage);
}
});
}
}
</script>

jQuery function does not get called for Html Helpers but gets called for it's equivalent html controls

I am a beginner in asp.net MVC.
I am using MVC 4 for my project and I am using strongly typed partial view and I render it in a View.
What I am trying to achieve is when a user enters a email address in Email Address textbox which is generated by #Html.EditorFor(model=>model.Email)
Html helper and when user looses focus on that textbox; a jQuery function
focusout will get called which will check if entered Email is already present in a database or not. Following is my code
#model PITCRoster.tblLoginDetail
#using (Html.BeginForm("AddUser","Resources",FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>tblLoginDetail</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model=>model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<p id="emailVerify"></p>
<div class="editor-label">
#Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.UserPassword)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserPassword)
#Html.ValidationMessageFor(model => model.UserPassword)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ConfirmPassword)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ConfirmPassword)
#Html.ValidationMessageFor(model => model.ConfirmPassword)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
and I have a jQuery function which is as follows
$("#Email").focusout(function () {
var emailData = $("#Email").val();
$.ajax({
url: '/Resources/CheckEmailAddress',
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
data: '{emailId:"' + emailData + '"}',
success: OnSuccess,
failure: function (data) {
alert('something went wrong!');
}
});
function OnSuccess(data) {
debugger;
if (!data) {
$("#emailVerify").css('color', 'green');
$("#emailVerify").html("Valid Email!");
}
if (data) {
$("#emailVerify").css('color', 'red');
$("#emailVerify").html("Email already registered!");
}
}
});
The jQuery function doesn't get called for the textbox created by Html Helper
But when I replace that Html helper with following code it runs properly.
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
<input type="email" class="text-box single-line" name="Email" value="" id="Email" data-val-required="The Email field is required." data-val-email="The Email field is not a valid e-mail address." data-val="true" />
#Html.ValidationMessageFor(model => model.Email)
</div>
CheckEmailAddress is a method in Resources controller.
Can anybody help me out why jQuery function doesn't get called when I use #Html.EditorFor(model=>model.Email)?
Assign an id and type to your model. By default it doesn't have an id of Email
#Html.TextBoxFor(x => x.Email, new {type="email", id="Email"})

Using javascript/AJAX in MVC Razor View?

I am supposed to convert a form submission from MVC Razor submission to an Ajax submission but I am having trouble even using simple javascript functions in the view of the form (Add.cshtml).
For starters, I try to link the JS file that i want to use in the following way:
#section JavaScript
{
<script type="text/javascript" src="#Url.Content("/Scripts/ajax_submit.js")"></script>
}
The javascript file looks like this:
function dosubmit() {
$("#add_address").ajaxForm({ url: '~/Home/Add', type: 'post' })
alert("IT WORKS");
return false;// if it's a link to prevent post
}
and I have my form built in the following way:
#model MvcApplicationTest.Models.PersonModel
#section JavaScript
{
<script type="text/javascript" src="#Url.Content("/Scripts/ajax_submit.js")"></script>
}
#{
ViewBag.Title = "Hinzufügen";
}
<h2>Hinzufügen</h2>
<form id="add_address">
<div class="fieldrow">
#Html.LabelFor(x => x.Nachname)
#Html.TextBoxFor(x => x.Nachname)
#Html.ValidationMessageFor(x => x.Nachname)
</div>
<div class="fieldrow">
#Html.LabelFor(x => x.Vorname)
#Html.TextBoxFor(x => x.Vorname)
#Html.ValidationMessageFor(x => x.Vorname)
</div>
<div class="fieldrow">
#Html.LabelFor(x => x.Strasse)
#Html.TextBoxFor(x => x.Strasse)
#Html.ValidationMessageFor(x => x.Strasse)
</div>
<div class="fieldrow">
#Html.LabelFor(x => x.Hausnummer)
#Html.TextBoxFor(x => x.Hausnummer)
#Html.ValidationMessageFor(x => x.Hausnummer)
</div>
<div class="fieldrow">
#Html.LabelFor(x => x.Plz)
#Html.TextBoxFor(x => x.Plz)
#Html.ValidationMessageFor(x => x.Plz)
</div>
<div class="fieldrow">
#Html.LabelFor(x => x.Ort)
#Html.TextBoxFor(x => x.Ort)
#Html.ValidationMessageFor(x => x.Ort)
</div>
<!--Martin-->
<div class="fieldrow">
#Html.LabelFor(x => x.Email)
#Html.TextBoxFor(x => x.Email)
#Html.ValidationMessageFor(x => x.Email)
</div>
<input type="button" onclick="dosubmit()" value="Speichern" />
</form>
However, when I click the button nothing happens (it should pop up a window with the desired text).
I have tried to include the JS file into the _Layout.cshtml, but it still doesn't work.
Thanks for your help :)
You should just need to call .ajaxForm on the form itself when the document is ready. .ajaxForm by itself just prepares the form for ajax submission, so by the time the submit button has been pressed, it's already too late.
I'd remove the submit handler from the submit button (I'd also use an input of type submit here):
<input type="submit" value="Speichern" />
and add the following:
$(function () {
$("#add_address").ajaxForm({
url: '~/Home/Add',
beforeSubmit: function () {
alert('about to submit');
},
type: 'post'
});
});
Alternatively you could use .ajaxSubmit instead of .ajaxForm:
function dosubmit() {
$("#add_address").ajaxSubmit({ url: '~/Home/Add', type: 'post' });
alert("IT WORKS");
return false;// if it's a link to prevent post
}

Implementing Search criteria using MVC return no record

I am trying to implement search criteria which bind to Kendo Ui grid. However it return no record and no error display. In SearchProduct it return the data but it would not bind to grid
Is there something i missed?
Controller code :
[HttpPost]
public ActionResult SearchProduct(ProductSearchCriteria criteria)
{
string nameCriteria = string.Empty;
string descCriteria = string.Empty;
TTSEntities dc = new TTSEntities();
if (!string.IsNullOrWhiteSpace(criteria.Name))
nameCriteria = criteria.Name.ToLower().Trim();
if (!string.IsNullOrWhiteSpace(criteria.Community))
descCriteria = criteria.Desc.ToLower().Trim();
var results = dc.Products.AsQueryable();
if (criteria.Name!= null)
results = results.Where(b => b.Name== criteria.Name);
if (criteria.Desc!= null)
results = results.Where(b => b.Desc== criteria.Desc);
return PartialView("_ProductGrid", results.ToList());
}
Index.cshtml :
#model HHIMS_Web_App.Models.ProductSearchCriteria
#using (Html.BeginForm())
{
<div id="headerpanel">
<fieldset>
<legend style="font-size:14px">Search Criteria</legend>
<div>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
</div>
</div>
<div>
<div class="editor-label">
#Html.LabelFor(model => model.Desc)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Desc)
</div>
<div class="smallBox">
<input type="button" value="Search" id="btnProductSearch" style="height:33px; font-size:14px; background-color:#3399FF" class="k-button" />
</div>
</div>
</fieldset>
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$('#btnProductSearch').click(function (e) {
var searchParameters = GetSearchParameters();
var jsonData = JSON.stringify(searchParameters, null, 2);
$.ajax({
url: '#Url.Content("~/ProductDetails/SearchProduct/")',
type: 'POST',
data: jsonData,
datatype: 'html',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#btnProductSearch').replaceWith(data);
},
error: function (request, status, err) {
alert(status);
alert(err);
}
});
});
function GetSearchParameters() {
var hrn = $("#Name").val();
var community = $("#Desc").val();
return { Name: name,
Desc: desc
};
}
});
</script>
_ProductGrid View :
<div>
<fieldset class="searchResults">
<legend style="font-size:14px">Search Result</legend>
<br />
<div>
#(Html.Kendo().Grid<TTP.Models.ProductModel>()
.Name("Product")
.HtmlAttributes(new { #Style = "align:center; font-size:10px; width:500px" })
.Columns(columns =>
{
columns.Bound(p => p.Name);
columns.Bound(p => p.Desc);
})
.AutoBind(false)
.Editable(editable => editable.Mode(GridEditMode.InLine))
.Sortable()
//.Pageable()
.Pageable(paging => paging
.Input(false)
.Numeric(true)
.PreviousNext(true)
.PageSizes(new int[] { 5, 10, 25, 50 })
.Refresh(false)
)
.Selectable()
.Scrollable()
.ColumnMenu(c => c.Columns(false))
.DataSource(dataSource => dataSource
.Ajax()//bind with Ajax instead server bind
.PageSize(10)
.ServerOperation(true)
.Model(model =>
{
model.Id(p => p.Name);
}
)
)
)
</div>
</fieldset>
</div>
Your SearchProduct action should return JSON data for the grid.
See the Kendo Grid Demo - choose the ASP.NET MVC tab and look at the IndexController.Products_Read code.
You want something like this:
public ActionResult SearchProduct(
ProductSearchCriteria criteria,
[DataSourceRequest] DataSourceRequest dsr
)
{
IQueryable<Product> query = ...
return Json( query.ToDataSourceResult( dsr ) );
}
To pass the search parameters as extra data with the read ajax request, use the Data method:
dataSource.Read( read => read.Data( "GetSearchParameters" ) )
See Kendo: Ajax Binding - Pass Additional Data to Action Method

Categories