Post data to MVC3 controller without pagerefresh - c#

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>

Related

How to pass form text value as a c# parameter on Razor Pages

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);
}

Is there any way to save an image file to Mongo DB using ASP.NET MVC?

i've been trying to create a program that saves user's input into Mongo DB, but when it comes to user's file, i am struggling, i have done a little research about how to do it using GridFs, can I use GridFS in C#? or do i have to find other ways to save the file to mongo db?
edit:
here is my controller
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MongoDB.Bson;
using MongoDB.Driver;
namespace officialaspnet.Controllers
{
public class vaccinationController : Controller
{
// GET: vaccination
public ActionResult Index()
{
return View();
}
public ActionResult Getuserdetail()
{
return View();
}
[HttpPost]
public ActionResult Saveuserdetail(string firstname, string lastname, string dob, string studentid, string gender, string email, string phonenumber, string address, string city, string zipcode, string state, HttpPostedFileBase file)
{
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("test1");
var collec = database.GetCollection<BsonDocument>("test");
var document = new BsonDocument
{
{"Firstname", firstname },
{"Lastname", lastname },
{"Date of birth", dob },
{"Student ID", studentid },
{"Gender", gender },
{"Email", email },
{"Phone number", phonenumber },
{"Address", address },
{"City", city },
{"Zipcode", zipcode },
{"State", state },
};
collec.InsertOneAsync(document);
return Content("Account created");
}
}
}
here is my form:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<!--providing css-->
<style>
body {
margin: 0;
padding: 0;
background: url() no-repeat;
background-size: cover;
font-family: sans-serif;
line-height: 2.6;
}
.topnav {
overflow: hidden;
background-color: whitesmoke;
}
.topnav a {
float: left;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: white;
color: black;
}
.topnav a.active {
background-color: black;
color: white;
}
.userinput-box {
width: 100%;
padding: 10px 0;
margin: 5px 0;
border-left: 0;
border-top: 0;
border-right: 0;
border-bottom: 1px;
outline: none;
background: transparent;
line-height: 2.6;
}
.userinput-group {
top: 180px;
position: absolute;
width: 280px;
line-height: 2.6;
}
.button {
background-color: #cbcbcb;
}
</style>
</head>
<body>
<script src=""></script>
<!--top nav-->
<div class="topnav">
<a class="active" href="">Log in</a>
Home
News
Contact
About
Shopping Cart
Billing info
</div>
<div class="register-box">
<center><h1><b>Covid Vaccine Verification form</b></h1></center>
<!--code for form-->
<form class="userinput-box" method="post" action="Saveuserdetail">
<center>
<!--giving 3 input field and defining their id-->
<h3>First name: <input type="text" name="firstname" id="firstname" required> Last name:<input type="text" name="lastname" id="lastname" required></h3>
<h3>Date of birth: <input type="date" name="dob" id="dob" required>Student ID: <input type="number" name="studentid" id="studenid" required></h3>
<h3>Gender: <input type="radio" id="male" name="gender" value="male"><label for="male">Male </label><input type="radio" id="female" name="gender" value="female"><label for="female">Female </label><input type="radio" id="other" name="gender" value="other"><label for="other">Other: </label><input type="text" name="othergender" id="othergender" /></h3>
<h3>Email: <input type="text" name="email" id="email" required> Phone#: <input type="number" name="phonenumber" id="phonehumber" required></h3>
<h3>Address: <input type="text" name="address" id="address" size="65" required></h3>
<h3>City: <input type="text" name="city" id="city" required> Zip code: <input type="number" name="zipcode" id="zipcode"> State: <input type="text" name="state" id="state" required></h3>
<h3>Add an attachment <input type="file" id="file" name="file" required ></h3>
<!--button for submitting-->
<br /><button type="submit" value="Save" class="button"><h3>Submit</h3></button>
</center>
</form>
</div>
</body>
</html>

Comment boxes only post with first post in MVC

I have a view in my MVC application that is designed to show views and comments gathered from a database, and allow users to make posts and comments accordingly.
The relevant section of Html is below:
<div style="background-color:#fff1fc; height:100vh; width:810px; float:left; border-radius: 8px; margin: 5px">
<div>
<p>
<center>
#foreach (var item in Model.PostList)
{
<div style="background-color: white; height:auto; width: 810px; border-radius: 8px; margin: 5px; text-align: left; text-size-adjust: 50%; text-anchor:start; font-size: larger">
#Html.DisplayFor(modelItem => item.Profile.FirstName)
#Html.DisplayFor(modelItem => item.Profile.LastName)
#Html.DisplayFor(modelItem => item.Project.ProjectName)<br/>
<div style="text-align:center; text-size-adjust: auto">
#Html.DisplayFor(modelItem => item.Text)<br/>
</div>
<div style="text-align: right; text-size-adjust: 20%; text-anchor: end">
#Html.DisplayFor(modelItem => item.DATE)
</div>
<hr />
<div style="line-break:initial; font-size:small; text-align: left; margin: 10px; padding: 10px">
#Html.Label("Comments:")<br/>
<br/>
#foreach (var comment in Model.CommentList)
{
if (comment.PostId == item.Id)
{
#Html.DisplayFor(modelComment => comment.Profile.FirstName)
#Html.DisplayFor(modelComment => comment.Profile.LastName)
<br/>
<center>
#Html.DisplayFor(modelComment => comment.Comment1)
<hr />
<br/>
</center>
}
}
<center>
#Html.TextAreaFor(model => Model.Comment, new { #class = "height: 200px, width: 600px"})
<br />
<br />
<right>
<input type="submit" value="Comment" class="btn btn-default" />
<input type="hidden" name="PostId" value="#item.Id" />
<input type="hidden" name="ProfileId" value="#Model.ProfileList[0].Id" />
</right>
<br />
</center>
</div>
</div>
}
</center>
</p>
</div>
</div>
So, for each item in PostList, the relevant attributes of that list are displayed. With these posts, each item from the CommentList that references this post is also displayed, with a TextBox to make a new comment. This all works fine! The problem appears to be here:
<center>
#Html.TextAreaFor(model => Model.Comment, new { #class = "height: 200px, width: 600px"})
<br />
<br />
<right>
<input type="submit" value="Comment" class="btn btn-default" />
<input type="hidden" name="PostId" value="#item.Id" />
<input type="hidden" name="ProfileId" value="#Model.ProfileList[0].Id" />
</right>
<br />
</center>
For some reason, when I attempt to make a comment on my platform, it only works if commenting on the most recent/first post on the feed (The first item). Attempting to make a comment on anything other than the first item, does nothing. Here is the Post method of my controller:
public ActionResult Post(string Text, int Id, string Comment, int ProfileId, int PostId)
{
if (Text != "")
{
using (var ctx = new SocialDBEntities())
{
string userId = User.Identity.GetUserId();
Post post = new CrowdSocial2.Post();
post.ProfileId = Id;
post.DATE = System.DateTime.Now.Date;
post.Text = Text;
db.Posts.Add(post);
db.SaveChanges();
return RedirectToAction("Feed");
}
}
else if (Comment != "")
{
string userId = User.Identity.GetUserId();
Comment comment = new CrowdSocial2.Comment();
comment.PostId = PostId;
comment.ProfileId = ProfileId;
comment.Comment1 = Comment;
comment.Date = System.DateTime.Now.Date;
db.Comments.Add(comment);
db.SaveChanges();
return RedirectToAction("Feed");
}
else
{
return RedirectToAction("Feed");
}
}
The controller is passed Comment, and determines whether or not it is "null". If not, it will post the comment to the database with the accompanying postId and profileId. Since this wasn't working, I decided to put a breakpoint on the RedirectToAction both inside of the if(Comment != "") statement, and in the elseif statement to see what was happening.
Turns out, Comment for some reason is being passed as "" regardless of what was written in the comment box, the controller is seeing it as "" and hence just redirects back to the view. This makes me suspect that what is happening is that Comment is being passed from the very first comment box, which is empty.
Any ideas how I can fix this so that I can comment on any of the post items?

Jquery validation with mvc is not working

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

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

Categories