On my login page I have a dropdownlist to change the culture of the application for which I am doing a Ajax call to set the culture. By default I have set to 'en_US'.
My issue is when I am login directly without changing the culture I am able to login successfully, but when I change the culture and tries to login, I am not able to do that. Is this happening because of AJAX call made, which makes custom attribute not registered ?
Also, my login method has a custom attribute defined. Below is the code.
AJAX Call
$('#ddlLanguages').change(function () {
var val = $('#ddlLanguages').val()
createCookie('culturecookie', val, 7);
$.ajax({
type: "POST",
url: '/Account/GetCultureNew',
data: { culturename: val },
success: function (result) {
$("#logo-group").html('');
$(document.body).html('');
$(document.body).html(result);
},
error: function (data) {
//alert('Error');
}
});
});
Ajax Method in controller
[HttpPost]
public ActionResult GetCultureNew(string culturename)
{
if (!string.IsNullOrEmpty(culturename) & culturename.Contains("#"))
{
string[] strdata = culturename.Split('#');
if (strdata.Length > 0)
{
AppTenant tenant = HttpContext.Session.GetObjectFromJson<AppTenant>("TenantInfo");
if (tenant != null)
{
tenant.LoggedInCulture = strdata[0];
tenant.LanguageID = Convert.ToInt32(strdata[1]);
HttpContext.Session.SetObjectAsJson("TenantInfo", tenant);
}
}
}
List<SelectListItem> items = new List<SelectListItem>();
items = HttpContext.Session.GetObjectFromJson<List<SelectListItem>>("LanguageData");
foreach (var item in items)
{
if (item.Value == culturename)
{
item.Selected = true;
}
else
{
item.Selected = false;
}
}
var itemsString = JsonConvert.SerializeObject(items);
CookieOptions obj = new CookieOptions();
obj.Expires = DateTime.Now.AddMonths(3);
Response.Cookies.Append("Languagelist", itemsString, obj);
var viewModel = new LMS_User { ReturnUrl = string.Empty, LanguageList = items };
return View("Login", viewModel);
}
Login Method
[HttpPost]
[AllowAnonymous]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
[Route("Admin/Login/{clietname}")]
public async Task<IActionResult> Login([Bind(include: "Email,Password,RememberMe")] LMS_User model, string returnUrl)
{
// my login logic
}
EDIT :- 1
Login partial View
<div class="col-xs-12 col-sm-12 col-md-5 col-lg-4">
<div class="well no-padding">
<form action="#Url.Action("login", "account")" method="POST" id="login-form" class="smart-form client-form">
<header>
#obj["SingnIn"]
</header>
#Html.AntiForgeryToken()
<fieldset>
<section>
<label asp-for="LanguageList">#obj["LanguageList"] </label>
#Html.DropDownList("Languages", Model.LanguageList, null, new { id = "ddlLanguages", #class = "form-control" })
</section>
<section>
<label asp-for="Email">#obj["Email"]</label>
<label class="input">
<i class="icon-append fa fa-user"></i>
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
<b class="tooltip tooltip-top-right"><i class="fa fa-user txt-color-teal"></i>>#obj["tooltipEmail"]</b>
<span asp-validation-for="Email" class="text-danger"></span>
</label>
</section>
<section>
<label asp-for="Password">#obj["Password"]</label>
<label class="input">
<i class="icon-append fa fa-lock"></i>
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
<b class="tooltip tooltip-top-right"><i class="fa fa-lock txt-color-teal"></i>#obj["tooltippassword"] </b>
<span asp-validation-for="Password" class="text-danger"></span>
</label>
<div class="note">
<i class="fa fa-frown-o"></i> #obj["Forgot_password?"]
</div>
</section>
<section>
<label class="checkbox">
<input asp-for="RememberMe" />
<i></i>#obj["Remember_Me"]
</label>
</section>
<footer>
<button type="submit" class="btn btn-primary">
#obj["SingnIn"]
</button>
</footer>
</fieldset>
</form>
</div>
#{ await Html.RenderPartialAsync("_SocialMedia"); }
Edit 2:-Entire login view
<div id="content" class="container">
<div class="row">
#{ await Html.RenderPartialAsync("_LoginText"); }
#{ await Html.RenderPartialAsync("_LoginPartial"); }
</div>
</div>
However if I add location.reload() in AJAX success function, then by changing the culture I can login successfully.
Any help on this appreciated !
When you do the $(document.body).html(result);
The action part of the form goes missing. Hence it does not know where to post to.
Hope i have been of some help :)
Related
I'm new to ASP.Net Core 2.1 MVC and C#,
I couldn't figure out what's wrong with the code.
I'm using Sweet Alerts as dialog confirmation before any post actions,
it works but it redirects instantly to the index page, the line below didn't even executed properly.
swal("Saved!", "Your record has been saved.", "success");
I want it to redirect to the index page only after the user clicks 'OK' and the alert closed properly (like fade out)
$(function () {
$("#btnSave").click(function (e) {
e.preventDefault();
swal({
title: "Save Changes?",
text: "",
type: "info",
showCancelButton: true,
cancelButtonClass: 'btn-secondary waves-effect',
confirmButtonClass: 'btn-success waves-effect waves-light',
confirmButtonText: "Yes",
closeOnConfirm: false
}, function () {
$("#studentForm").submit();
swal("Saved!", "Your record has been saved.", "success");
});
});
});
I tried switching the lines
$("#studentForm").submit();
swal("Saved!", "Your record has been saved.", "success");
to
swal("Saved!", "Your record has been saved.", "success");
$("#studentForm").submit();
but it didn't work.
This is my Edit view:
#model CIMS.Models.Plans
#{
ViewData["Title"] = "Edit";
}
<div class="row">
<div class="col-xs-12">
<div class="page-title-box">
<h4 class="page-title">Edit Plan</h4>
<div class="clearfix"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="card-box table-responsive">
<form asp-action="Edit" id="studentForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="PlanID" />
<div class="form-group">
<label asp-for="PlanName" class="control-label">Plan Name</label>
<input asp-for="PlanName" class="form-control" />
<span asp-validation-for="PlanName" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Description" class="control-label"></label>
<input asp-for="Description" class="form-control" />
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="BillCutOffLimit" class="control-label">Bill Cut-off Limit</label>
<input asp-for="BillCutOffLimit" class="form-control" />
<span asp-validation-for="BillCutOffLimit" class="text-danger"></span>
</div>
<br />
<div class="form-group">
<button type="submit" value="Save" class="btn btn-success waves-effect waves-light w-sm" id="btnSave">
<span class="btn-label"><i class="fa fa-check"></i></span>
Save
</button>
<a asp-action="Index" class="btn btn-primary waves-effect waves-light w-sm">
<span class="btn-label"><i class="fa fa-arrow-left"></i></span>
Back
</a>
</div>
</form>
</div>
</div>
</div>
and this is the http post edit action under the controller:
// POST: Plans/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(string id, [Bind("PlanID,PlanName,Description,BillCutOffLimit,ModifiedBy,DateModified,ModifiedByComputerUsed")] Plans plans)
{
if (id != plans.PlanID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Attach(plans);
plans.ModifiedBy = User.Identity.Name;
plans.DateModified = DateTime.Now;
plans.ModifiedByComputerUsed = Environment.MachineName;
_context.Entry(plans).Property(x => x.PlanName).IsModified = true;
_context.Entry(plans).Property(x => x.Description).IsModified = true;
_context.Entry(plans).Property(x => x.BillCutOffLimit).IsModified = true;
_context.Entry(plans).Property(x => x.DateModified).IsModified = true;
_context.Entry(plans).Property(x => x.ModifiedBy).IsModified = true;
_context.Entry(plans).Property(x => x.DateModified).IsModified = true;
//_context.Update(plans);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!PlansExists(plans.PlanID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(plans);
}
any idea?
Not sure which version of sweetalert.js you are using but the below code works with 2.1.0 of https://sweetalert.js.org/
You need to use the Promise based design for sweetalert . When you click on the first confirm before saving the changes it returns a Promise of boolean value which signifies whether the user has confirmed the action or not. You need to resolve the promise to check this boolean value.Based on this value you need to create another instance of swal and similarly resolve it to make the Ajax call like below -
sample code for Ajax call
$(function () {
$("#btnSave").click(function (e) {
e.preventDefault();
swal({
title: "Save Changes?",
text: "",
type: "info",
showCancelButton: true,
cancelButtonClass: 'btn-secondary waves-effect',
confirmButtonClass: 'btn-success waves-effect waves-light',
confirmButtonText: "Yes",
closeOnConfirm: false
})
.then(val => {
if (!val) throw null;
swal("Saved!", "Your record has been saved.", "success")
.then((confirm) => {
$("#studentForm").submit();
})
});
});
$("#studentForm").on('submit',function(){
alert('form POST');
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"></script>
<link href="http://tristanedwards.me/u/SweetAlert/lib/sweet-alert.css" rel="stylesheet"/>
<form id="studentForm" method="POST">
name : <input type="text" id="fullname" /> <br>
<button id="btnSave">
Save
</button>
</form>
Working fiddle : http://jsfiddle.net/3e7fgtop/
Single page having three different registration form,based on single ID reference, I need to call the three different [HttpPost] ActionResult method ,when i click the submit button for first form it's goes to first action result method correctly.
<div class="page-content">
<div class="container-fluid">
<header class="section-header">
<div class="tbl">
<div class="tbl-row">
<div class="tbl-cell">
<h2>Company Registration Form</h2>
</div>
</div>
</div>
</header>
#using (Html.BeginForm(FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<section class="tabs-section">
<div class="tabs-section-nav tabs-section-nav-icons">
<div class="tbl">
<ul class="nav" role="tablist">
<li class="nav-item">
<a class="nav-link active" href="#tabs-1-tab-1" role="tab" data-toggle="tab">
<span class="nav-link-in">
<i class="font-icon font-icon-cogwheel"></i>
Company Registration Form
</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#tabs-1-tab-2" role="tab" data-toggle="tab">
<span class="nav-link-in">
<span class="glyphicon glyphicon-music"></span>
Company Social Network
</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#tabs-1-tab-3" role="tab" data-toggle="tab">
<span class="nav-link-in">
<i class="fa fa-product-hunt"></i>
Company Reference
</span>
</a>
</li>
</ul>
</div>
</div><!--.tabs-section-nav-->
<div class="tab-content">
<div role="tabpanel" class="tab-pane fade in active show" id="tabs-1-tab-1">
<br />
<br />
<section>
<div>
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model =>Model.company.CompanyName, new { #class = "form-label semibold control-label" })
#Html.TextBoxFor(model => model.company.CompanyName, new { #class = "form-control", placeholder = "Enter the Company Name" })
#Html.ValidationMessageFor(model => model.company.CompanyName)
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.ShortName, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.ShortName, new { #class = "form-control", placeholder = "Enter the Short Name" })
#Html.ValidationMessageFor(model => model.company.ShortName)
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.Division, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.Division, new { #class = "form-control", placeholder = "Enter the Division" })
#Html.ValidationMessageFor(model => model.company.Division)
</fieldset>
</div>
</div><!--.row-->
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.company.Email, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.company.Email, new { #class = "form-control", placeholder = "Enter your Email" })
#Html.ValidationMessageFor(model => model.company.Email)
</fieldset>
</div>
</div><!--.row-->
</div>
</section>
<input type="submit" name="Submit" id="Save" value="Save" class="btn btn-rounded btn-inline btn-success" onclick=" GetInfo();" />
</div><!--.tab-pane-->
<div role="tabpanel" class="tab-pane fade" id="tabs-1-tab-2">
<br />
<section>
<div>
<div class="row">
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanySocial.FaceBookID, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.CompanySocial.FaceBookID, new { #class = "form-control", placeholder = "Enter the Facebook Link" })
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanySocial.TwitterID, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.CompanySocial.TwitterID, new { #class = "form-control", placeholder = "Enter the Twitter Link" })
</fieldset>
</div>
<div class="col-lg-4">
<fieldset class="form-group">
#Html.LabelFor(model => model.CompanySocial.linkedinID, new { #class = "form-label semibold" })
#Html.TextBoxFor(model => model.CompanySocial.linkedinID, new { #class = "form-control", placeholder = "Enter the Linkedin Link" })
</fieldset>
</div>
</div><!--.row-->
</div>
</section>
<input type="submit" name="Submit" value="Previous" class="btn btn-rounded btn-inline btn-primary prev-step" />
<input type="submit" name="Submit" id="Save" value="Next" class="btn btn-rounded btn-inline btn-success" onclick="GetInfo1();" />
</div><!--.tab-pane-->
<div role="tabpanel" class="tab-pane fade" id="tabs-1-tab-3">
Tab 3
<br /><br />
<input type="submit" name="Submit" value="Previous" class="btn btn-rounded btn-inline btn-primary prev-step" />
<input type="submit" name="Submit" value="Finish" class="btn btn-rounded btn-inline btn-success" />
</div><!--.tab-pane-->
</div><!--.tab-content-->
</section><!--.tabs-section-->
}
</div>
</div>
ActionResult Code:
[HttpPost]
public ActionResult AddCompany(MainModel cmp)
{
try
{
if (ModelState.IsValid)
{
}
return View();
}
catch
{
return View();
}
}
When i click second Submit button it's again going to the same ActionResult AddCompany(MainModel cmp) but i need to go to ActionResult AddSocial(MainModel Social)
Here this code :
[HttpPost]
public ActionResult AddSocial(MainModel Social)
{
try
{
if (ModelState.IsValid)
{
//ScriptManager.RegisterStartupScript(this, typeof(Page), "paginationClickHandler", "paginationClickHandler();", true);
}
return View();
}
catch
{
return View();
}
}
Ajax Method:
function GetInfo() {
var company = { companyName: document.getElementById('CompanyName').value, shortName: document.getElementById('ShortName').value, division: document.getElementById('Division').value, Email: document.getElementById('Email').value }
$.ajax({
type: "POST",
url: "/Company/AddCompany",
data: '{cmp:' + JSON.stringify(company) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
function GetInfo1() {
var Social = { faceBook: document.getElementById('FaceBook').value, twitter: document.getElementById('Twitter').value, linkedin: document.getElementById('linkedin').value }
$.ajax({
type: "POST",
url: "/Company/AddSocial",
data: '{Social:' + JSON.stringify(Social) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
Your button is still inside a form. So when you handle your button click in javascript, you need to make sure to prevent the default behavior of a submit button click inside a form ( the form submit).
Using unobtrusive javascript way, give a unique id to your button
<input type="submit" id="saveSocial" value="Next" />
and now, bind click event on this button, prevent the default behavior using
jquery preventDefault method and call your js method.
$(document).ready(function() {
$("#saveSocial").click(function(e) {
e.preventDefault();
GetInfo1();
});
});
Also it does not make sense to return a full view from your action method when the call is from ajax code. May be you should return a json response.
A submit inside the form is going to post the form, even if you have an onclick action written. If you want it to instead call the javascript function, change the <input> to a <button> or <a> tag.
EDIT
Delete the form tag completely to prevent submission which is reloading your page.
net mvc 5 application and for this I use bootstrap because it looks fine.
I don't want to use for an input and a searchbutton the
#using (Html.BeginForm("...
Can I control the html tags without this from my controller. For example here is my index.cshtml
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
<div class="row">
<h2>Suche</h2>
<div id="custom-search-input">
<div class="input-group col-md-12">
<input type="text" class=" search-query form-control" placeholder="Search" />
<span class="input-group-btn">
<button class="btn btn-danger" type="button">
<span class=" glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</div>
</div>
</div>
I want if I click on the Searchbutton I get a message with the text from the inputfield.
Here is the Controller:
public ActionResult Search(string value)
{
//listofUsers is a arraylist of all users that found^^
return View(listofUsers);
}
How I can do this? :)
Add a div to show the result:
<div id="custom-search-input">
<div class="input-group col-md-12">
<input type="text" class=" search-query form-control" placeholder="Search" />
<span class="input-group-btn">
<button class="btn btn-danger" type="button">
<span class=" glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</div>
<div class="custom-search-result"></div>
Then in a script tag or a linked js file:
$(document).ready(function () {
$('.custom-search-input').each(function () {
var sinput = $(this);
var svalue = sinput.find('input');
var sresult = sinput.next('.custom-search-result');
sinput.find('button').click(function () {
$.ajax({
url: '/ControllerName/Search?value=' + svalue.val(),
type: 'GET'
}).done(function (result) {
sresult.html(result);
});
});
});
});
This is a basic example with no error handling.
First I highly recommend reading Philip Walton (Google) - Decoupling your HTML, CSS and Javascript, it's extremely good.
Here how I would use MVC to it's full potential.
Model:
// Extensible Programming
// Using a string limits additional features
// Future proofing via a class that takes 2 minutes to create
public class GlobalSearch
{
public string SearchTerms { get; set; }
}
View:
#Model GlobalSearch
<div class="container">
<div class="row">
<h2>Suche</h2>
<div id="custom-search-input">
#using (Html.BeginForm("Search"))
{
<div class="input-group col-md-12">
#Html.TextBoxFor(m => m.SearchTerms, new {
#class="search-query form-control",
placeholder="Search" })
<span class="input-group-btn">
<button class="btn btn-danger" type="button">
<span class=" glyphicon glyphicon-search js-form-submit"></span>
</button>
</span>
</div>
}
</div>
</div>
</div>
Controller:
// Strongly Typed Class is Returned
public ActionResult Search(GlobalSearch search)
{
return View(listofUsers);
}
The following script will require this fantastic script called form2js which correctly converts any strongly-typed forms generated by MVC (arrays, lists etc) into Json that will be ModelBinded correctly.
$(document).ready(function() {
('.js-form-submit').on('click', function() {
var $form = $(this).closest('form');
var json = form2js($form);
var ajaxSettings = {
url: $form.attr('action'),
type: $form.attr('method'),
data: json,
contentType: "application/json",
}
$.ajax(ajaxSettings)
.done()
.always()
.fail();
});
});
Of course this could be easily abstract into it's own javascript class/namespace that returns the promise and reusable on any form that simply has a button with the class js-form-submit instead of continually rewriting $.ajax over and over again each time for different forms.
I'm fairly new to asp .net MVC, I've got a modal wish accepts a username, email address, comments, and also has a submit button. I'm looking create the submit functionality such that when it's pressed it'll send an email.
I've had passed experience sending emails in c# no problem, the troubles I'm having is linking the two together.
<div class="modal fade" id="contact" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal">
<div class="modal-header">
<h4>Contact Tech Site</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="contact-name" class="col-lg-2 control-label">Name:</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="contact-name" placeholder="Full Name">
</div>
</div>
<div class="form-group">
<label for="contact-email" class="col-lg-2 control-label">Email:</label>
<div class="col-lg-10">
<input type="email" class="form-control" id="contact-email" placeholder="you#example.com">
</div>
</div>
<div class="form-group">
<label for="contact-msg" class="col-lg-2 control-label">Message:</label>
<div class="col-lg-10">
<textarea class="form-control" rows="8"></textarea>
</div>
</div>
</div>
<div class="modal-footer">
<a class="btn btn-default" data-dismiss="modal">Close</a>
<button class="btn btn-primary" type="submit">Send</button>
</div>
</form>
</div>
</div>
</div>
Email Code
var SMTP_USERNAME = User.EmailUsername;
var SMTP_PASSWORD = EncryptionHelper.Decrypt(User.EmailPassword);
Mail.Subject = Subject;
Mail.Body = EmailText;
foreach (var to in SelectedUsers)
{
foreach (var contactMethod in to.ContactMethods.Where(x => x.Primary && x.Channel == ContactMethod.Channels.Email))
{
Mail.To.Add(contactMethod.Value);
}
}
Mail.From = new MailAddress(SMTP_USERNAME, User.FullName());
//Server
var HOST = unitOfWork.SettingRepository.GetString(KnownKeys.SMTPServer);
//Port
var PORT = int.Parse(unitOfWork.SettingRepository.GetString(KnownKeys.SMTPPort));
// Create an SMTP client with the specified host name and port.
var emailSent = false;
using (SmtpClient client = new SmtpClient(HOST, PORT))
{
// Create a network credential with your SMTP user name and password.
client.Credentials = new System.Net.NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
// Use SSL when accessing Amazon SES. The SMTP session will begin on an unencrypted connection, and then
// the client will issue a STARTTLS command to upgrade to an encrypted connection using SSL.
client.EnableSsl = true;
// Send the email.
try
{
client.Send(Mail);
emailSent = true;
}
catch (Exception ex)
{
MessageBox.Show("Error message: " + ex.Message);
}
}
Create a model -
public class EmailViewModel
{
public string Username { get; set; }
public string Email { get; set; }
public string Comments { get; set; }
}
And then create your controller -
public class HomeController : Controller
{
public ActionResult GetEmailForm()
{
return View();
}
public ActionResult SubmitEmail(EmailViewModel model)
{
var result = SendEamil(model);
return View();
}
private bool SendEamil(EmailViewModel model)
{
// Use model and send email with your code.
return true;
}
}
Basically GetEmailForm action will return you a view with form -
#model MvcApplication1.Controllers.EmailViewModel
#{
ViewBag.Title = "GetEmailForm";
}
<h2>GetEmailForm</h2>
<link href="../../Content/bootstrap.css" rel="stylesheet" />
#using (Html.BeginForm("SubmitEmail", "Home", FormMethod.Post))
{
<div id="contact">
<div class="modal-dialog">
<div class="modal-content">
<form class="form-horizontal">
<div class="modal-header">
<h4>Contact Tech Site</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="contact-name" class="col-lg-2 control-label">Name:</label>
<div class="col-lg-10">
#Html.TextBoxFor(m => m.Username, new { #placeholder = "Full Name"})
</div>
</div>
<div class="form-group">
<label for="contact-email" class="col-lg-2 control-label">Email:</label>
<div class="col-lg-10">
#Html.TextBoxFor(m => m.Email, new { #placeholder = "you#example.com"})
</div>
</div>
<div class="form-group">
<label for="contact-msg" class="col-lg-2 control-label">Message:</label>
<div class="col-lg-10">
#Html.TextAreaFor(m => m.Comments, new { #placeholder = "Comments"})
</div>
</div>
</div>
<div class="modal-footer">
<a class="btn btn-default" data-dismiss="modal">Close</a>
<button class="btn btn-primary" type="submit">Send</button>
</div>
</form>
</div>
</div>
</div>
}
When you enter data and click on submit, it will post the viewmodel with data to SubmitEmail action of same controller.
Output of the page is as shown below, sorry for styles, i have no time so removed some of the styles.
When you enter data and click on submit, you get data as shown below -
Once you have the data, you can use that in your private method SendEmail (which will have your code) to send email.
Check the MSDN site for information on how to create a form, it will get submitted when the user presses the submit button. Back in yoru controller add a second version of your method with the HttpPost attribute and give it a parameter instance of your model, MVC will take care of the mapping for you. See BUILDING ASP.NET MVC FORMS WITH RAZOR for more details.
Call a action method From your Email Controller thru a ajax call.From the below Code Snippet you will get an idea how to do it.
$('#btnSubmit').on('click', function () { //Ur Button
$.ajax({
type: "POST",
url: "/EmailController/SendEmailAction",
data: "{Email:" + $("#contact-email").val() +"}", // Reading from extboxes and Converting to JSON for Post to EmailController Action
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
//alert message
//Close the Modal
}
});
});
And In C# level in youecontroller
public JsonResult _SendEmail(EmailViewModel model)
{
//Here your code to send Email
}
I hope now you will get an idea how to go about it.
I think you do not require a form and submit button to send an email from a bootstrap modal.
While developing an ASP.NET MVC 4 application I ran into a problem updating a saved image.
Basically when the user selects the edit tab, their re-directed to the content they previously entered.
One such item of that content is an image, and when in the edit menu they can choose to replace the existing image.
I have the other content updating correctly but the image remains the same, when I place a breakpoint on the "edit" ActionResult, it show the image value for the passing model as null? newsArticle.ArticleImage = Null
FYI - Image is saved as a byte array.
Am I missing something ?
Controller....
[HttpPost]
public ActionResult Edit(NewsArticle newsArticle, int id, HttpPostedFileBase Article)
{
try
{
if (ModelState.IsValid)
{
NewsArticle savedArticle= _newsArticle.Get(id);
savedArticle.Body = newsArticle.Body;
savedArticle.Title = newsArticle.Title;
if (newsArticle.ArticleImage == null)
{
newsArticle.ArticleImage = savedArticle.ArticleImage;
}
else
{
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
newsArticle.ArticleImage = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
savedArticle.ArticleImage = newsArticle.ArticleImage;
}
if (newsArticle.ImageName == null)
{
newsArticle.ImageName = savedArticle.ImageName;
}
else
{
string imgeName = Path.GetFileName(Article.FileName);
savedArticle.ImageName = imgeName;
}
_uow.SaveChanges();
return RedirectToAction("Index");
}
}
catch (System.Data.DataException)
{
//Log th error(add a variable name after DataExpection)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(newsArticle);
}
View..........
#using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", #class = "form-horizontal", id = "newsEditForm" }))
{
#Html.ValidationSummary()
#Html.HiddenFor(model => model.ID)
<div class="control-group">
<label class="control-label">Posted on :</label>
<div class="controls">
<span class="text">#Model.DateCreated.Value.ToShortDateString()</span>
#*#Html.LabelFor(n => n.DateCreated)*#
</div>
</div>
<div class="control-group">
<label class="control-label">#Html.LabelFor(n => n.Title)</label>
<div class="controls">
#Html.TextBoxFor(n => n.Title, new { #class = "span4 m-wrap", rows = 1 })
</div>
</div>
<div class="control-group">
<label class="control-label">#Html.LabelFor(n => n.Body)</label>
<div class="controls">
#Html.TextAreaFor(n => n.Body, new { #class = "span12 ckeditor m-wrap", rows = 4 })
</div>
</div>
<div class="control-group">
<label class="controls">#Html.DisplayTextFor(model => model.ImageName)</label>
<div class="span4 blog-img blog-tag-data">
<div class="editor-field">
<input type="file" name="Article" id="ArticleImage" />
</div>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn green" id="submitnews"><i class="icon-ok"></i>Submit</button>
#Html.ActionLink("Cancel", "ArticleList", "Admin", null, new { #class = "btn blue" })
#*<button type="button" class="btn blue" onclick="location.href='ArticleList','Admin'">Cancel</button>*#
</div>
}