I have a contact page in mvc . I have a 4 text box in this page and
one text area and i want to give validation using jquery the
text-box id is txtbxName, txtbxCompany, txtbxEmail, txtbxPhone ,and
txtarMessage. when user click on submit button if txtbxName is blank.
i want a message something like this "Please enter your Name!" and so
on. please help me thanks
ContactController.cs
public ViewResult Create(string Name, string Company, string Regarding, string Email, string Phone, string Message)
{
string body = "Name: " + Name + "<br>" + "\nCompany: " + Company + "<br>" + "Regarding: " + Regarding + "<br>" + "Email: " +
Email + "<br>" + "Phone: " + Phone + "<br>" + "Message: " + Message;
try
{ MailMessage mail = new MailMessage(); mail.From = new MailAddress("g#technosys.com");
mail.To.Add("p#technosys.com");
mail.Subject = "Accept Request";
mail.Body = body;
mail.IsBodyHtml = true; SmtpClient smtp = new SmtpClient("smtp.gmail.com");
smtp.Credentials = new System.Net.NetworkCredential("g#technosys.com", "1457898");
smtp.EnableSsl = true;
// smtp.UseDefaultCredentials = true;
smtp.Send(mail);
}
catch (Exception ex)
{
ViewData.ModelState.AddModelError("_FORM", ex.ToString());
}
return View();
Jquery
$("#btnSubmit").click(function (event) {
var data = { Name: $("#txtbxName").val(), Company: $("#txtbxCompany").val(), Regarding:
$("#ddlRegarding").val(), Email: $("#txtbxEmail").val(), Phone: $("#txtbxPhone").val(), Message:
$("#txtarMessage").val()
}
$.ajax({
type: "POST",
url: "/Contact/Create", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
dataType: "html",
success: function (result) {
$("#txtbxName").val("");
$("#txtbxCompany").val("");
$("#txtbxEmail").val("");
$("#txtbxPhone").val("");
$("#txtarMessage").val("");
alert(result);
// Or if you are returning something
alert('I returned... ' + result.WhateverIsReturning);
},
error: function (result) {
$("#txtbxName").val("");
$("#txtbxCompany").val("");
$("#txtbxEmail").val("");
$("#txtbxPhone").val("");
$("#txtarMessage").val("");
alert('Thanks for sending info');
return false;
}
});
});
Index .cshtml
<div class="parteners">
<div class="block" style="width: 270px;">
<div class="block" style="width: 295px; padding: 3px;">
Name :
</div>
<div class="block" style="width: 320px; padding: 3px;">
<input type="text" class="textbox" name="textfield" alt="Type our Name here" />> <br />
</div>
<div class="block" style="width: 295px; padding: 3px;">
Company :
</div>
<div class="block" style="width: 295px; padding: 3px;">
<input type="text" class="textbox" name="textfield2" />
</div>
<div class="block" style="width: 295px; padding: 3px;">
Regarding :
</div>
<div class="block" style="width: 295px; padding: 3px;">
<select name="select" class="textbox">
<option>General Inquiry</option>
<option>Programming Related Question</option>
<option>Website Quote Request</option>
<option>Feedback</option>
<option>Help and Support</option>
</select>
</div>
</div>
<div class="block" style="width: 270px;">
<div class="block" style="width: 295px; padding: 3px;">
Email :</div>
<div class="block" style="width: 295px; padding: 3px;">
<input type="text" class="textbox" name="textfield3" />
</div>
<div class="block" style="width: 295px; padding: 3px;">
Phone :
</div>
<div class="block" style="width: 295px; padding: 3px;">
<input type="text" class="textbox" name="textfield4" />
</div>
</div>
<div class="block" style="width: 600px; padding: 3px;">
Enter your Suggestions / Comments / Feedback here :
</div>
<br />
<div class="block" style="width: 600px; padding: 3px;">
<textarea class="textarea" name="textarea"></textarea><br />
<br />
</div>
<div class="block" style="width: 600px; padding: 3px;">
<input id="Button1" type="Button" value="Submit" />
</div>
</div>
Set class to all the textboxes like below
<input type="text" class="valcheck" title="Name" id="your_name_field_id" name="your_name_field_name" />
do the same for all the 6 textboxes.
$("#btnSubmit").click(function (event) {
$(".valcheck").each(function(){
var id = this.id;
var field_value = $("#"+id).val();
if(field_value=="")
{
var field_name = $("#"+id).attr('title');
$("#error_display_div").append("Please enter "+field_name+"<br />");
}
//Show hide error_display_div accordingly, you can clear out the div using
// $("#error_display_div").html('');
});
});
You should look into the jQuery validation plugin: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
You should consider using a ViewModel like this:
public class MessageVM
{
public string CompanyName {get;set;}
[Required]
public string Name {get;set;}
public string Regarding {get;set;}
public string Message {get;set;}
[Required]
public string Email {get;set;}
}
Which uses DataAnnotations. You use this in your view to bind to like so:
#Model Your.Namespace.ViewModels.MessageVM
#using(Html.BeingForm("create"))
{
#Html.LabelFor(x => x.Name)
#Html.TextBoxFor(x => x.Name)
#Html.LabelFor(x => x.CompanyName)
#Html.TextBoxFor(x => x.CompanyName)
#Html.LabelFor(x => x.Regarding)
#Html.TextBoxFor(x => x.Regarding)
#Html.LabelFor(x => x.Email)
#Html.TextBoxFor(x => x.Email)
#Html.LabelFor(x => x.Message)
#Html.TextBoxFor(x => x.Message)
<button type="submit">Send!</button>
}
And then you can set up a method on your controller something like the below
public ActionResult Create(MessageVM message)
{
if (!ModelState.IsValid)
{
return View(message);
}
//else do whatever you need, send the email etc.
}
Bit more here
Related
I have a function that fetch the data based on the user's registration number on the active directory and print it to the textbox fields on the modal. In that case I need to send as a parameter whatever is written in the textbox instead of the field numbered 31919 in the code below.
<center>
<image style="margin-top: 20px; width: 25%;" src="/images/adduser.png"></image>
<div style="margin-top: 25px;">
<form method="post">
<label class="control-label"><b>Reg. No</b></label>
<input type="text" name="RegNo" id="RegNo" value="">
<button onclick="created(1)" style="margin-left: 15px; height: 60%;" data-toggle="modal" data-target="#AddUser1" type="button" class="btn btn-light-primary px-6 font-weight-bold">Fetch</button>
<span id="spin"><i style="position: relative; display: inline-block;" class="fas fa-sync fa-spin"></i></span>
</form>
#{
FetchDataFromAD("31919");
}
<hr />
</div>
</center>
So, basically I'm trying to do something like this:
#{
FetchDataFromAD(RegNo.Text);
}
P.S.: FetchDataFromAD just a function that modifying string expressions like that:
public void FetchDataFromAD(string RegNo)
{
System.DirectoryServices.DirectorySearcher search = new System.DirectoryServices.DirectorySearcher(directoryEntry);
search.Filter = "(postalCode=" + RegNo + ")";
foreach (System.DirectoryServices.SearchResult sResultSet in search.FindAll())
{
// Ad
FetchADPersonelName = GetProperty(sResultSet, "cn");
FetchADTitle = GetProperty(sResultSet, "title");
FetchADNetworkN = GetProperty(sResultSet, "samaccountname");
FetchADEmail = GetProperty(sResultSet, "mail");
FetchADAdress = "2";
// FetchADDepartman = GetProperty(sResultSet, "department");
}
}
How can I achieve that? Thank you for any suggestions.
Consider to use the following:
<script>
function ApplyFilter() {
var regno = document.getElementById("RegNo").value;
$.ajax({
type: "GET",
url: '#Url.Action("FetchDataFromAD", "Home")',
contentType: "application/json;charset=utf-8",
data: { regno },
dataType: "json",
success: function (data) {
}
});
};
</script>
<div style="margin-top: 25px;">
<form method="post">
<label class="control-label"><b>Reg. No</b></label>
<input type="text" name="RegNo" id="RegNo" value="">
<button onclick="ApplyFilter()" style="margin-left: 15px; height: 60%;" data-toggle="modal" data-target="#AddUser1" type="button" class="btn btn-light-primary px-6 font-weight-bold">Fetch</button>
<span id="spin"><i style="position: relative; display: inline-block;" class="fas fa-sync fa-spin"></i></span>
</form>
<hr />
</div>
And the FetchDataFromAD() method signature update to be called from JavaScript:
public JsonResult FetchDataFromAD(string RegNo)
{
... your code here
return Json("Filter is applied", JsonRequestBehavior.AllowGet);
}
I have a method in my controller called "NewJobApp" that works fine and returns the view with "NewJobApp" model.
[AllowAnonymous]
[HttpGet("Consultant/NewJobApp/{agencyID:int}/{userID:int}/{companyID:int}/{jobID:int}")]
public async Task<ViewResult> NewJobApp(int agencyID, int userID, int companyID, int jobID)
{
NewJobApp nja = await Repository.GetNewJobApp(agencyID, userID, companyID, jobID);
return View(nja);
}
In the view I have a form that should call "SubmitNewJobApp", but when I view the page source, it shows action=""
<form id="JobAppForm" class="form-group" asp-controller="Consultant" asp-action="SubmitNewJobApp" method="post" style="text-align: left">
#Html.AntiForgeryToken()
<input id="AgencyID" asp-for="#Model.AgencyID" value="#Model.AgencyID" type="hidden" />
<input asp-for="#Model.AgencyName" value="#Model.AgencyName" type="hidden" />
<input asp-for="#Model.UserID" value="#Model.UserID" type="hidden" />
<input asp-for="#Model.CompanyID" value="#Model.CompanyID" type="hidden" />
<input asp-for="#Model.JobID" value="#Model.JobID" type="hidden" />
#if (!String.IsNullOrEmpty(Model.Errs))
{
#Html.Raw(Model.Errs);
}
<p style="margin: 0px; font-size: 8px"> </p>
<div class="form-group">
<label style="width: 120px; text-align: left; display: inline-block;" asp-for="#Model.JobTitle">Job:</label>
<input type="text" asp-for="#Model.JobTitle" value="#Model.JobTitle" readonly />
</div>
<div class="form-group">
<label style="width: 120px; text-align: left; display: inline-block;" asp-for="#Model.CompanyName">Company:</label>
<input type="text" asp-for="#Model.CompanyName" value="#Model.CompanyName" readonly />
</div>
<p style="margin-bottom: 4px;">Enter person search expression:</p>
<input asp-for="#Model.SearchExpression" value="#Model.SearchExpression" style="width: 132px; margin-bottom: 8px;" />
<button id="myButton" class="btn btn-primary" type="submit">Get Candidates</button>
<p style="margin: 0px; font-size: 8px"> </p>
<div class="form-group">
<label style="width: 120px; display: inline-block;" asp-for="ContactID">Contact:</label>
#Html.DropDownListFor(m => m.ContactID, Model.Contacts, "Choose a Contact", new { #class = "myDDL", #id = "contactsDDL" })
</div>
<div class="text-center" style="text-align: right">
<button id="btnSave" class="btn btn-primary" type="submit">Save</button>
</div>
</form>
This is the "SubmitNewJobApp" method in the controller, but it never gets called.
[HttpPost()]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SubmitNewJobApp(NewJobApp nj)
{
int id = 0;
bool is_err = false;
string err = string.Empty;
// check data
if (nj.ContactID == 0)
{
is_err = true;
}
// check model state
if (!ModelState.IsValid || is_err)
{
nj = await Repository.GetNewJobApp(nj);
return View("NewJobApp", nj);
}
nj.NewRecordID = id;
return View("NewJobApp", nj);
}
I still don't understand why this doesn't work, but I have a temporary solution.
If I remove the HttpGet template on the method that returns the "NewJobApp" view, the form action now contains a value, and works!
Previous method:
[AllowAnonymous]
[HttpGet("Consultant/NewJobApp/{agencyID:int}/{userID:int}/{companyID:int}/{jobID:int}")]
public async Task<ViewResult> NewJobApp(int agencyID, int userID, int companyID, int jobID)
{
NewJobApp nja = await Repository.GetNewJobApp(agencyID, userID, companyID, jobID);
return View(nja);
}
Now changed to:
[HttpGet()]
[AllowAnonymous]
public async Task<ViewResult> NewJobApp(int agencyID, int userID, int companyID, int jobID)
{
NewJobApp nja = await Repository.GetNewJobApp(agencyID, userID, companyID, jobID);
return View(nja);
}
This is the changed code that calls the "NewJobApp" controller method:
function startNewApplicant() {
var para1 = #ViewBag.AgencyID;
var para2 = #Model.Job.UserID;
var para3 = #Model.Job.CompanyID;
var para4 = #Model.Job.JobID;
// var url = "NewJobApp/" + para1 + "/" + para2 + "/" + para3 + "/" + para4; (previous)
var url = "NewJobApp?agencyID=" + para1 + "&userID=" + para2 + "&companyID=" + para3 + "&jobID=" + para4;
window.open(url, '_blank');
}
But actually I prefer to use the template because I want the cleaner looking URL.
My Startup routes:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "signin",
template: "{controller=Home}/{action=Index}/{agencyID}/{contactID}");
});
I am currently learning Angular Js . I added the ADO.NET Entitly model in my project and Angular Js Packages as well. I am unable to do insert like user registration from my registration page. I lunch the developer tools and its showing following error ...
Module.js:5 Uncaught ReferenceError: angular is not defined
at Module.js:5
at Module.js:60
user.png Failed to load resource: the server responded with a status of 404 (Not Found)
load.png Failed to load resource: the server responded with a status of 404 (Not Found)
angular.min.js:42 Uncaught Error: [$injector:modulerr]
Here is my Code in Module.js file under MyScript Folder..
var app;
(function () {
var app = angular.module("myApp", []);
app.controller("Ctrl", ['$scope', function ($scope){
$scope.SaveUser = function () {
$("#divLoading").show();
var User = {
FName: $scope.fName,
LName: $scope.lName,
Email: $scope.uEmail,
Password: $scope.uPwd,
UserName: $scope.uName
};
var response = myService.AddUser(User);
response.then(function (data) {
if (data.data == "1") {
$("#divLoading").hide();
clearFields();
alert("User Created !");
window.location.href = "/Register/Login";
}
else if (data.data == "-1") {
$("#divLoading").hide();
alert("user alraedy present !");
}
else {
$("#divLoading").hide();
clearFields();
alert("Invalid data entered !");
}
});
}
function clearFields() {
$scope.fName = "";
$scope.lName = "";
$scope.Email = "";
$scope.Password = "";
$scope.UserName = "";
}
}]);
app.service("myService", function ($http) {
this.AddUser = function (User) {
var response = $http({
method: "post",
url: "/Register/AddUser",
data: JSON.stringify(User),
dataType: "json"
});
return response;
}
})
})();
Here is my code in controller.The name of my controller is RegisterController ..
public class RegisterController : Controller
{
public ActionResult Register()
{
return View();
}
//To check that user entered is already present or not.
public bool CheckUser(string user)
{
bool Exists = false;
using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
{
var uName = context.UserLogins.Where(x => x.UserName == user).ToList();
if (uName.Count != 0)
{
Exists = true;
}
}
return Exists;
}
//For saving the user details in database table.
public string AddUser(UserLogin usr)
{
if (usr != null)
{
if (CheckUser(usr.UserName) == false)
{
using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
{
UserLogin createUser = new UserLogin();
createUser.UserName = usr.UserName;
createUser.Firstname = usr.Firstname;
createUser.Lastname = usr.Lastname;
createUser.Email = usr.Email;
createUser.DateTimeCreated = DateTime.Now;
createUser.Password = Utility.Encryptpassword(usr.Password);
context.UserLogins.Add(createUser);
context.SaveChanges();
}
return "User created !";
}
else
{
return "User already present !";
}
}
else
{
return "Invalid Data !";
}
}
}
}
Here is HTML CODE ...
#{
Layout = null;
}
<html ng-app="myApp">
<head>
<title>Register</title>
<script src="~/Scripts/MyScript/Module.js"></script>
<script src="~/Scripts/angular.min.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
</head>
<body>
<div class="container" ng-controller="myCntrl">
<br />
<div class="row">
<img src="~/Content/Images/user.png" /><h4>Register User</h4>
<hr />
<br />
<div class="col-md-6">
<form name="userForm" novalidate>
<div class="form-horizontal">
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
First Name :
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="First Name" name="fName" ng-model="fName" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
Last Name :
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="Last Name" name="lName" ng-model="lName" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de">
Email :
</div>
<div class="col-md-6">
<input type="email" class="form-control" placeholder="User's Email" name="uEmail" ng-model="uEmail" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
Username :
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="Username" name="uName" ng-model="uName" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">
Password :
</div>
<div class="col-md-6">
<input type="password" class="form-control" placeholder="Password" name="uPwd" ng-model="uPwd" required autofocus />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-3">
<input type="button" value="Save" ng-click="SaveUser();" class="btn btn-success" />
</div>
<div class="col-md-3">
#Html.ActionLink("Sign in", "Login", "Register", new { #class = "btn btn-info" })
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<div id="divLoading" style="margin: 0px; padding: 0px; position: fixed; right: 0px; top: 0px; width: 100%; height: 100%; background-color: #666666; z-index: 30001; opacity: .8; filter: alpha(opacity=70); display: none">
<p style="position: absolute; top: 30%; left: 45%; color: White;">
please wait...<img src="~/Content/images/load.png">
</p>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Here is Screen Shot when I run the application Click here ]1
Any one help me to solved this Error
remove the first var app;
It is like you are declaring the app twice, try this
var app = angular.module("myApp", [])
.controller('myCntrl',['$scope',function($scope){
// your code here
}])
.service();
UPDATE
In the Module.js, you have defined the name of your controller app.controller("Ctrl",), but in the html File when you're calling it, you wrote ng-controller='myCntrl'
You have to give them the same name, that's it
I am using jquery vaidation in mvc and it is working every where
except in one view which contains other view like so :
#{
Layout = Request.IsAjaxRequest() ? null :"~/Views/Shared/FormsView.cshtml";
}
<div id="indexdiv">
<style>
.ma {
padding-left: 5px;
padding-top: 8px;
}
.blueb {
padding-left: 10px;
padding-bottom: 10px;
padding-top: 8px;
}
.add {
margin-bottom: 5px;
width: 500px;
}
</style>
<div class="btn-danger ma ci" style="height:50px ;">
<h2 class="white" style=" float:left; margin-left:5px ; margin-top:2px; margin-bottom:10px;"> ADDRESSES </h2>
<button id="sh" class="btn btn-primary" style="float:right; margin-right:5px;">
#Ajax.ActionLink(
"Create",
"Create",
"Addresses",
new AjaxOptions
{
UpdateTargetId = "EditDivId",
InsertionMode = InsertionMode.Replace
})
</button>
</div>
<div id="EditDivId">
</div>
<div class="nicdark_space10"></div>
#{ Html.RenderAction("_i"); }
#{ Html.RenderAction("Index", "Emails"); }
#{ Html.RenderAction("Index", "Phones"); }
my create action returns this partial view which where the validation doesn't work :
#model CourseSelection.Models.Address
<style>
.ma {
padding-left: 5px;
padding-top: 8px;
}
.blueb {
padding-left: 10px;
padding-bottom: 10px;
padding-top: 8px;
background-color: green;
}
.add {
margin-bottom: 5px;
width: 500px;
}
.mr {
margin-right: 20px;
}
.link {
color: brown;
}
.link:hover {
color: brown;
}
</style>
#Scripts.Render("~/bundles/jquery")
#using (Ajax.BeginForm("Create", "Addresses", FormMethod.Post, new AjaxOptions
{
UpdateTargetId = "indexdiv",
InsertionMode = InsertionMode.Replace
}, new { #id = "createform22" }))
{
#Html.AntiForgeryToken()
<div id="tt">
<div class="blueb nicdark_bg_blue" style="margin-top:10px;">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="addres">Address</label>
<br />
<input type="text" class="form-control add" id="address1" name="address1" maxlength="100" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="type">Type</label>
<br />
#Html.DropDownList("typeid", null, htmlAttributes: new { #class = "form-control" })
</div>
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for="city">City</label>
<select id="Countries" name="cityid" class="form-control"></select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="county">County</label>
<select id="States" name="countyid" class="form-control"></select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="neighborhood">Neighborhood</label>
<input type="text" placeholder="neighborhood" class="form-control" id="neighborhood" name="neighborhood" />
</div>
</div>
<div class="form-group">
<div class="col-md-1">
<label for="s"></label>
<br />
<input type="submit" value="Create" class="btn btn-primary" id="s1" style="margin-top:6px; width:80px; height:35px;" />
</div>
<div class="col-md-1">
<label for="hi"></label>
<input type="reset" value="Cancel" class="btn btn-danger" id="hi5" style="margin-top:6px; margin-left:3px; width:80px; height:35px;" />
</div>
</div>
</div>
</div>
</div>
}
#section scripts {
<script type="text/javascript">
$(function () {
$.getJSON("/Addresses/cities/List", function (data) {
var items = "<option>Select City</option>";
$.each(data, function (i, country) {
var selected = "";
items += "<option value='" + country.Value + "'>" + country.Text + "</option>";
});
$("#Countries").html(items);
});
$("#Countries").change(function () {
var x = $("#Countries > option:selected").attr("value");
$.getJSON("/Addresses/towns/List/" + x, function (data) {
var items = "<option>Select Town</option>";
$.each(data, function (i, town) {
items += "<option value='" + town.Value + "'>" + town.Text + "</option>";
});
$("#States").html(items);
});
});
});
</script>
}
<script>
$("#hi").click(function () {
$("#tt").hide();
});
$("#createform22").validate({
onkeyup: false,
onclick: false,
rules: {
address1: {
required: true,
email: true
},
},
messages: {
address1: {
required: "Please enter an email",
email: "Email Is not valid"
},
},
errorPlacement: function (error, element) {
swal({ title: "", text: error.text(), imageUrl: "/img/warning.png" });
}
});
</script>
here is my email index view where the validation work :
#{
Layout = Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/empty.cshtml";
}
<style>
.ma {
padding-left: 5px;
padding-top: 8px;
}
.blueb {
padding-left: 10px;
padding-bottom: 10px;
padding-top: 8px;
}
.add {
margin-bottom: 5px;
width: 500px;
}
</style>
<div class="btn-danger ma ci" style="height:50px ;">
<h2 class="white" style=" float:left; margin-left:5px ; margin-top:2px; margin-bottom:10px;"> Emails </h2>
<button id="sh" class="btn btn-primary" style="float:right; margin-right:5px;">
#Ajax.ActionLink(
"Create",
"Create",
"Emails",
new AjaxOptions
{
UpdateTargetId = "EditDivId1",
InsertionMode = InsertionMode.Replace
})
</button>
</div>
<div id="EditDivId1">
</div>
<div class="nicdark_space10"></div>
#{ Html.RenderAction("_i"); }
<script>
</script>
Try to use validations into viewmodels. Client validation in Asp.net
I have this script that basically has 4 select boxes, what I want is that for the 2 top select boxes, he submits the optionvalue that is selected to an action (which can be found at "ProductKoppeling/ProductKoppelingPartial"), I want to let him submit this data when I click on an option but without page refresh.
I tried JSON and I tried Ajax, but I didn't get it working..
How should i do this?
Script:
<script language="javascript" type="text/javascript">
function delete_1() {
var answer = confirm("U staat op het punt dit product te verwijderen, wilt u doorgaan?")
if (answer) {
document.getElementById('Actie_1').value = '5';
document.getElementById('hpg_submit').submit();
}
}
function delete_2() {
var answer = confirm("U staat op het punt dit product te verwijderen, wilt u doorgaan?")
if (answer) {
document.getElementById('Actie_2').value = '6';
document.getElementById('pg_submit').submit();
}
}
function delete_3() {
var answer = confirm("U staat op het punt dit product te verwijderen, wilt u doorgaan?")
if (answer) {
document.getElementById('Actie_3').value = '6';
document.getElementById('p_submit').submit();
}
}
</script>
CSHTML:
<div style="width: 500px; float: left;">
#using (Html.BeginForm("ProductKoppelingPartial", "ProductKoppeling", FormMethod.Post, new { id = "onload_submit" }))
{
#Html.DropDownList("Klant.Id", (ViewBag.Klant as SelectList), new { onchange = "document.getElementById('onload_submit').submit()" })
}
<div style="clear: both"></div>
<div style="float: left;">
<b>Hoofdgroepen</b><br />
#using (Html.BeginForm("ProductKoppelingPartial", "ProductKoppeling", FormMethod.Post, new { id = "hpg_submit" }))
{
if (ViewBag.SelectedKlant != null)
{
<input type="hidden" name="Klant.Id" value="#ViewBag.SelectedKlant.Id" />
}
<select style="width: 200px;" size="6" id="HoofdProductGroep" name="HoofdProductGroep.Id" onchange="document.getElementById('hpg_submit').submit();">
#foreach (var hpg in ViewBag.HoofdProductGroep)
{
if (ViewBag.SelectedHPG != null)
{
if (hpg.Id == ViewBag.SelectedHPG.Id)
{
<option value="#hpg.Id" selected="selected">#hpg.Naam</option>
}
else
{
<option value="#hpg.Id">#hpg.Naam</option>
}
}
else
{
<option value="#hpg.Id">#hpg.Naam</option>
}
}
</select>
<input type="hidden" name="Actie" id="Actie_1" value="0" />
<br />
<img src="../../Content/toevoegen.png" style="cursor: pointer; width: 30px;" onclick="document.getElementById('Actie_1').value='1';document.getElementById('hpg_submit').submit();" />
<img src="../../Content/bewerken.png" style="cursor: pointer; float: none; width: 30px;" onclick="document.getElementById('Actie_1').value='2';document.getElementById('hpg_submit').submit();" />
<img src="../../Content/verwijderen.png" style="cursor: pointer; float: none; width: 30px;" onclick="delete_1()" />
}
</div>
<div style="float: right;">
<b>Groepen</b><br />
#using (Html.BeginForm("ProductKoppelingPartial", "ProductKoppeling", FormMethod.Post, new { id = "pg_submit" }))
{
if (ViewBag.SelectedHPG != null)
{
<input type="hidden" name="HoofdProductGroep.Id" value="#ViewBag.SelectedHPG.Id" />
}
if (ViewBag.SelectedKlant != null)
{
<input type="hidden" name="Klant.Id" value="#ViewBag.SelectedKlant.Id" />
}
<select size="6" style="width: 200px;" id="ProductGroep_Id" name="ProductGroep.Id" onchange="document.getElementById('pg_submit').submit();">
#foreach (var pg in ViewBag.ProductGroep)
{
if (ViewBag.SelectedPG != null)
{
if (pg.Id == ViewBag.SelectedPG.Id)
{
<option value="#pg.Id" selected="selected">#pg.Naam</option>
}
else
{
<option value="#pg.Id">#pg.Naam</option>
}
}
else
{
<option value="#pg.Id">#pg.Naam</option>
}
}
</select>
<input type="hidden" name="Actie" id="Actie_2" value="0" />
<br />
<img src="../../Content/toevoegen.png" style="cursor: pointer; width: 30px;" onclick="document.getElementById('Actie_2').value='3';document.getElementById('pg_submit').submit();" />
<img src="../../Content/bewerken.png" style="cursor: pointer; float: none; width: 30px;" onclick="document.getElementById('Actie_2').value='4';document.getElementById('pg_submit').submit();" />
<img src="../../Content/verwijderen.png" style="cursor: pointer; float: none; width: 30px;" onclick="delete_2()" />
}
</div>
<div style="clear: both; height: 25px;"></div>
#using (Html.BeginForm("Save", "ProductKoppeling", FormMethod.Post, new { id = "p_submit" }))
{
<div style="float: left">
<b>Producten</b><br />
<select size="18" style="width: 200px;" name="Product.Id">
#foreach (var p in ViewBag.Product)
{
<option value="#p.Id">#p.Naam</option>
}
</select>
#if (ViewBag.SelectedPG != null)
{
if (ViewBag.SelectedPG.Id != null)
{
<input type="hidden" name="ProductGroep.Id" value="#ViewBag.SelectedPG.Id" />
}
}
<input type="hidden" name="Actie" id="Actie_3" value="0" />
<br />
<img src="../../Content/toevoegen.png" style="cursor: pointer; width: 30px;" onclick="document.getElementById('Actie_3').value='1';document.getElementById('p_submit').submit();" />
<img src="../../Content/bewerken.png" style="cursor: pointer; float: none; width: 30px;" onclick="document.getElementById('Actie_3').value='2';document.getElementById('p_submit').submit();" />
<img src="../../Content/verwijderen.png" style="cursor: pointer; float: none; width: 30px;" onclick="delete_3()" />
<br />
</div>
<div style="float: left; width: 100px;">
<center>
<br /><br /><br /><br />
<a style="cursor: pointer; float: none; color: blue; font-size: 30px;" onclick="document.getElementById('p_submit').submit();">»</a>
<br /><br /><br /><br /><br /><br /><br /><br /><br />
<a style="cursor: pointer; float: none; color: blue; font-size: 30px;" onclick="document.getElementById('pgp_submit').submit();">«</a>
</center>
</div>
}
<div style="float: right;">
<b>Producten in groepen</b><br />
#using (Html.BeginForm("Delete", "ProductKoppeling", FormMethod.Post, new { id = "pgp_submit" }))
{
<select size="18" style="width: 200px;" name="ProductGroepProduct.Id">
#foreach (var pgp in ViewBag.ProductGroepProduct)
{
if (pgp != null)
{
if (pgp.Product != null)
{
<option value="#pgp.Id">#pgp.Product.Naam</option>
}
}
}
</select>
}
</div>
You are using a Html Form.
This causes a refresh by default.
Use an ajax form or don't use forms at all and just call an action but don't return an action result.
Create a controller similar to:
public void Action(String paramater)
{
...
}
When you call it from the view it will execute the code on the server side without causing any effects on the client.
As Requested:
Added Non refresh Ajax form example:
$.ajax({
type: "POST",
url: "URL",
data: dataString,
success: function() {
...
};
});
return false;
The return false prevents a refresh.
Follow this guide for a full tutorial.
Maybe you should use Ajax calls ... and choose the div you wish to refresh : here is a short example :
AjaxOptions ajaxOptions = new AjaxOptions
{
HttpMethod = "Post",
UpdateTargetId = "Mydiv",
OnSuccess = "aJqueryFunction"
};
And in your ajax call :
<div id="Mydiv">
#using (Ajax.BeginForm("text", "Action",(optional)"Cotroller", ajaxOptions))
{}
</div>