Jquery validation with mvc is not working - c#

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

Related

Does not enter controller from # url.action

I have a problem, it does not return anything to me and it does not enter my controller. Someone knows why
<div class="col-xs-12 input-group input-group-sm">
<span style="padding: 2px 20px 0px 50px;"><strong>Ingrese Código de la Imagen:</strong></span>
<div class="form-validator" style="padding: 2px 10px 0px 350px;">
<div style="float: left;">
<img id="CaptchaImg" src="#Url.Action("ShowCaptchaImage", "Account", new { random = Guid.NewGuid().ToString() })" alt="" />
</div>
<div style="float: left;">
<img alt="" src="" class="invoice img_refresh" id="refresh" onclick="RecargaCaptcha('#Url.Action("ShowCaptchaImage", "Account")');" />
</div>
#Html.TextBoxFor(m => m.PasswordNuevo, new { #class = "form-control input-sm", style = "width:500px;" })
</div>
</div>
My Controller:
[Authorize]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
public CaptchaImageResult ShowCaptchaImage(string random)
{
return new CaptchaImageResult();
}

A controller with this name is not registered in Angulaj Js with Sql Database

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

How to differentiate between selection and save in MVC post

I have a form which has a DropDownList to select users and a form for user data. All controls are nested inside a form.
Cureently user DropDownList submits the form to notify about user selection to fetch appropriate data.
I want have a Button type(submit) which saves the data for the current user. Since both controls are in the same form and they both do submit, how can I differentiate if I am trying to select the user or saving the data in my action?
I have tried creating two forms as follows:
#model MyApp.Models.UserModel
#{
ViewBag.Title = "Profiles";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript" src="chosen.jquery.js"></script>
<script type="text/javascript" src="bootstrap-switch.js"></script>
<link rel="stylesheet" href="chosen.css" />
<link rel="stylesheet" href="bootstrap-switch.css" />
<style type="text/css">
.chosen-search{
display: none;
}
.form-group label{
margin-top: 10px;
}
.row{
margin-bottom: 20px;
}
th{
text-align: center;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$('#CurrentUserId').chosen({placeholder_text_single: "Select a user"});
$('#CurrentGroupId').chosen({placeholder_text_single: "Select a group"});
$('#CurrentRoleId').chosen({placeholder_text_single: "Select a role"});
$('#IsActive').bootstrapSwitch({
onColor: "success",
offColor: "danger",
onText: "ACTIVE",
offText: "PASSIVE",
animate: false,
handleWidth: 60
});
$('.authorizationCheckBox').bootstrapSwitch({
onColor: "success",
offColor: "danger",
onText: "Y",
offText: "N",
animate: false,
size: "mini"
});
});
</script>
#using (Html.BeginForm("Profile", "User"))
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-sm-3">
<div class="row">
<label class="control-label">Selected user :</label>
</div>
</div>
<div class="col-sm-9">
<div class="row">
#Html.DropDownListFor(x => x.CurrentUserId, new SelectList(Model.AllUsers, "Id", "Username"), "", new { #class = "form-control", onchange = #"this.form.submit();" })
</div>
</div>
</div>
}
#using (Html.BeginForm("SaveProfile", "User"))
{
if (!string.IsNullOrWhiteSpace(Model.CurrentUser))
{
<div class="row">
<div class="col-sm-3">
<div class="row">
#if (string.IsNullOrWhiteSpace(Model.UserImageUrl))
{
<img src="no-user.png" class="img-circle" alt="..." style="width: 35%; display: block; margin: auto;">
<button type="button" class="btn btn-primary" style="display: block; margin: auto; margin-top: 10px;">
<span class="glyphicon glyphicon-upload"></span> Upload avatar
</button>
}
else
{
<img src="#Model.UserImageUrl" class="img-circle" alt="..." style="width: 35%; display: block; margin: auto;">
<button type="button" class="btn btn-primary" style="display: block; margin: auto; margin-top: 10px;">
<span class="glyphicon glyphicon-retweet"></span> Change avatar
</button>
}
</div>
<div class="row">
<div class="input-group" style="margin: 0 auto;">
<div class="switch-button xlg showcase-switch-button">
#Html.CheckBoxFor(x => x.IsActive)
</div>
</div>
</div>
</div>
<div class="col-sm-9">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-2">Username :</label>
<div class="col-sm-10">
<input id="CurrentUser" name="CurrentUser" class="form-control form-control-flat" value="#Model.CurrentUser" />
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-2">E-mail :</label>
<div class="col-sm-10">
<input id="EMail" name="EMail" class="form-control form-control-flat" value="#Model.EMail" />
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-2">Membership :</label>
<div class="col-sm-10">
#Html.DropDownListFor(x => x.CurrentGroupId, new SelectList(Model.AllGroups, "Id", "Name"), "", new { #class = "form-control" })
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<label class="control-label col-sm-2">Role :</label>
<div class="col-sm-10">
#Html.DropDownListFor(x => x.CurrentRoleId, new SelectList(Model.AllRoles, "Id", "Name"), "", new { #class = "form-control" })
</div>
</div>
</div>
</div>
</div>
<button id="btnSave" type="submit" class="btn btn-info" style="float: right; margin-right: 10px; margin-bottom: 40px;">
<span class="glyphicon glyphicon-trash"></span>Save changes
</button>
}
}
[HttpGet]
public ActionResult Profile()
{
return View(CreateInitialUserModel());
}
[HttpPost]
public ActionResult Profile(UserModel model)
{
model = GetUserModel(model.CurrentUserId.Value);
ModelState.Clear();
return View(model);
}
[HttpPost]
public ActionResult SaveProfile(UserModel model)
{
SaveModel(model)
return RedirectToAction("Profile");
}
But the problem is, at HttpPost of Profile action works well. But when I click the Save button and the HttpPost SaveProfile action is called, input parameter model does not have the values set on the screen.
I would actually use two forms. Not only does it relieve your problem here, as you can just add a hidden field or something to each form to indicate which was submitted, but it prevents other issues you're likely to run into, like failing validation on any required user fields in the create form, when you just select a user, because no data was submitted for those fields.
Short of that, just use whatever JavaScript you're already using to automatically submit when an option is selected from the drop down to change a value of a hidden field or otherwise modify the post data before it's submitted.
Why not use jquery for data retrieval? You could switch you dropdown to instead call a jquery function that performs an ajax call to a controller method that retrieves the relevant user data. Then, you can bind the data to the appropriate fields on the page using jquery. You would then only have one submit button on your view, handled through the normal mvc form process.
-in drop downdown list change event ,you should store UserID to a variable like global variable or hiddenfields.
-Create a Button
in function=
function submitvalues()
{
//get stored userID here from variable
//perform submit here
}

Apply validation on textboxes in MVC using jQuery

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

Post data to MVC3 controller without pagerefresh

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>

Categories