I have this error when I try to enter on my system.
The provided anti-forgery token was meant for user "Braian ", but the current user is "".
My controller:
// GET: Account
[AllowAnonymous]
public ActionResult Login(/*string? returnURL*/)
{
System.Web.Security.FormsAuthentication.SignOut();
ModelState.Clear();
/*Recebe a url que o usuário tentou acessar*/
//ViewBag.ReturnUrl = returnURL;
return View(new TB_USUARIO());
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(TB_USUARIO login, string returnUrl)
{
System.Web.Security.FormsAuthentication.SignOut();
ModelState.Clear();
if (ModelState.IsValid)
{
using (DB_DAGUILAREntities db = new DB_DAGUILAREntities())
{
var vLogin = db.TB_USUARIO.Where(p => p.USU_ST_LOGIN.Equals(login.USU_ST_LOGIN)).FirstOrDefault();
/*Verificar se a variavel vLogin está vazia. Isso pode ocorrer caso o usuário não existe.
Caso não exista ele vai cair na condição else.*/
if (vLogin != null)
{
/*Código abaixo verifica se o usuário que retornou na variavel tem está
ativo. Caso não esteja cai direto no else*/
if (Equals(vLogin.USU_CH_ATIVO, "A"))
{
/*Código abaixo verifica se a senha digitada no site é igual a senha que está sendo retornada
do banco. Caso não cai direto no else*/
if (Equals(vLogin.USU_ST_SENHA.Trim(), login.USU_ST_SENHA))
{
FormsAuthentication.SetAuthCookie(vLogin.USU_ST_LOGIN, false);
if (Url.IsLocalUrl(returnUrl)
&& returnUrl.Length > 1
&& returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//")
&& returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
/*código abaixo cria uma session para armazenar o nome do usuário*/
Session["Nome"] = vLogin.USU_ST_NOME;
Session["Codigo"] = vLogin.USU_IN_CODIGO;
/*código abaixo cria uma session para armazenar o sobrenome do usuário*/
Session["Sobrenome"] = vLogin.USU_ST_LAST_NAME;
Session["Cargo"] = vLogin.USU_ST_CARGO;
Session["Especialidade"] = vLogin.USU_ST_ESPEC;
Session["Foto"] = vLogin.USU_ST_FOTO;
/*retorna para a tela inicial do Home*/
return RedirectToAction("Index", "Ticket");
}
/*Else responsável da validação da senha*/
else
{
/*Escreve na tela a mensagem de erro informada*/
ModelState.AddModelError("", "Senha informada Inválida!!!");
/*Retorna a tela de login*/
return View(new TB_USUARIO());
}
}
/*Else responsável por verificar se o usuário está ativo*/
else
{
/*Escreve na tela a mensagem de erro informada*/
ModelState.AddModelError("", "Usuário sem acesso para usar o sistema!!!");
/*Retorna a tela de login*/
return View(new TB_USUARIO());
}
}
/*Else responsável por verificar se o usuário existe*/
else
{
/*Escreve na tela a mensagem de erro informada*/
ModelState.AddModelError("", "E-mail informado inválido!!!");
/*Retorna a tela de login*/
return View(new TB_USUARIO());
}
}
}
/*Caso os campos não esteja de acordo com a solicitação retorna a tela de login com as mensagem dos campos*/
return View(login);
}
and my view:
#model WebApplication3.Models.TB_USUARIO
#{
Layout = null;
}
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<script src="~/scripts/jquery-1.10.2.js"></script>
<script src="~/scripts/bootstrap.min.js"></script>
#using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal" }))
{
#Html.AntiForgeryToken();
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="container">
<div class="form-login">
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-title">Login do Sistema</div>
</div>
<div style="padding-top:30px" class="panel-body">
<div style="display:none" id="result" class="alert alert-danger col-sm-12">
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
#Html.EditorFor(model => model.USU_ST_LOGIN, new { htmlAttributes = new { #class = "form-control input-lg", placeholder = "E-mail", autofocus = true } })
#Html.ValidationMessageFor(model => model.USU_ST_LOGIN, "", new { #class = "text-danger" })
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
#Html.EditorFor(model => model.USU_ST_SENHA, new { htmlAttributes = new { #class = "form-control input-lg", placeholder = "Senha" } })
#Html.ValidationMessageFor(model => model.USU_ST_SENHA, "", new { #class = "text-danger" })
</div>
<div style="margin-top:10px" class="form-group">
<div class="col-sm-12 controls">
<input type="submit" value="Acessar" class="btn primary btn-lg" />
</div>
</div>
</div>
</div>
</div>
</div>
}
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
The problem happened when:
Logon the system
Log out the system
try to logon with the same user.
Can someone help?
Related
I got stucked with (it seems to be) a simple problem.
My goal is to create a modal with an Ajax form. A child action gets the modal in a partial view, and when edited, submit button posts Ajax form which returns just Json data. Built-in code in Ajax.BeginForm should trigger OnSuccess or OnFailure depending on the result of the action.
The problem is OnFailure is triggered and OnSuccess don't, although the action finishes OK, and post return a 200 code. The "data" param in OnFailure function contains the HTML of the whole page.
This is the code:
(1) Snippet to load the modal in the main view:
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
#Html.Action("GetDialogV2", "Fianzas", new { idArrendamiento = Model.Id_Arrendamiento })
</div>
(2) Button to open the modal in the main view:
<button type="button" class="btn btn-outline-primary" data-toggle="modal" data-target="#exampleModal">
<i class="far fa-hand-holding-usd"></i> Modal
</button>
(3) The partial view with the modal (and the Ajax Form), GetDialogV2.cshtml:
#model EditFianzas_vm
#{
AjaxOptions ajaxOptions = new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "Respuesta",
OnSuccess = "OnSuccess",
OnFailure = "OnFailure"
};
}
#using (Ajax.BeginForm(ajaxOptions))
{
#Html.AntiForgeryToken()
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Fianza</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.Id_Arrendamiento)
<div class="form-group">
#Html.LabelFor(model => model.Importe, new { #class = "control-label col-md-6" })
<div class="col-md-8">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-euro-sign"></i></span>
</div>
#Html.EditorFor(model => model.Importe, new { htmlAttributes = new { #class = "form-control importe" } })
</div>
#Html.ValidationMessageFor(model => model.Importe, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Fecha_Abono, new { #class = "control-label col-md-6" })
<div class="col-md-8">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-calendar"></i></span>
</div>
#Html.TextBoxFor(model => model.Fecha_Abono, "{0:dd/MM/yyyy}", new { #class = "form-control datepicker" })
</div>
#Html.ValidationMessageFor(model => model.Fecha_Abono, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-8">
<input type="text" id="Respuesta" class="form-control" />
</div>
</div>
</div>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary" id="botonPrueba">Guardar</button>
</div>
</div>
<!-- /.modal-content -->
</div>
}
(4) The Javascript in the main view:
#section scripts
{
<script type="text/javascript">
function OnSuccess(data) {
if (data.Success == true) {
toastr.success("Operación realizada.", "Fianzas");
$("#exampleModal").modal('hide');
}
else {
if (data.modelState) {
$.each(d.modelState, function (i, item) {
toastr.info(i + ': ' + item, "i: item");
//item.valid(); //run jQuery validation to display error
$('#' + i).valid();
});
}
else {
toastr.error(data.Error, "Fianzas");
}
}
}
function OnFailure(data) {
alert(data);
alert('HTTP Status Code: ' + data.param1 + ' Error Message: ' + data.param2);
toastr.error("Se ha producido un error no controlado al realizar la operación.", "Fianzas");
toastr.warning(data, "Fianzas");
}
</script>
}
(5) And finally, the controller:
#region Ajax Form (GetDialogV2)
public PartialViewResult GetDialogV2(int idArrendamiento)
{
//Obtengo el modelo...
Arrendamientos_Fianzas fianza = db.Arrendamientos_Fianzas.Find(idArrendamiento);
//Creo la vista-modelo...
EditFianzas_vm vm = new EditFianzas_vm {
Id_Arrendamiento = idArrendamiento,
Importe = fianza.Importe,
Fecha_Abono = fianza.Fecha_Abono
};
return PartialView(vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult GetDialogV2(EditFianzas_vm vm)
{
try
{
if (!ModelState.IsValid)
{
var modelState = ModelState.ToDictionary
(
kvp => kvp.Key,
kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
);
modelState.Add("hdId_Arrendamiento", modelState["vm.Id_Arrendamiento"]);
modelState.Remove("vm.Id_Arrendamiento");
modelState.Add("txtImporte", modelState["vm.Importe"]);
modelState.Remove("vm.Importe");
modelState.Add("txtFecha_Abono", modelState["vm.Fecha_Abono"]);
modelState.Remove("vm.Fecha_Abono");
return Json(new { modelState }, JsonRequestBehavior.AllowGet);
//throw (new Exception("Error en la validación del modelo."));
}
//Miro a ver si existen datos para este arrendamiento (no sé si es un edit o un new, si quiero hacerlo todo en una misma acción)
Arrendamientos_Fianzas fianza = db.Arrendamientos_Fianzas.Find(vm.Id_Arrendamiento);
//Compruebo si es nuevo o editado...
if (fianza == null)
{
//Nuevo registro...
fianza = new Arrendamientos_Fianzas
{
Id_Arrendamiento = vm.Id_Arrendamiento,
Importe = vm.Importe,
Fecha_Abono = vm.Fecha_Abono
};
//Actualizo info de control...
fianza.C_Fecha = DateTime.Now;
fianza.C_IdUsuario = Usuario.NombreUsuario;
fianza.C_Comentarios = "Alta de la fianza.";
//Guardo registro...
db.Arrendamientos_Fianzas.Add(fianza);
}
else
{
//Estoy editando, grabo valores...
fianza.Importe = vm.Importe;
fianza.Fecha_Abono = vm.Fecha_Abono;
//Actualizo info de control...
fianza.C_Fecha = DateTime.Now;
fianza.C_IdUsuario = Usuario.NombreUsuario;
fianza.C_Comentarios = "Modificación de los datos de la fianza.";
//Modifico estado del registro en el modelo...
db.Entry(fianza).State = EntityState.Modified;
}
//Guardo cambios...
db.SaveChanges();
//Return...
return new JsonResult() { Data = Json(new { Success = true }) };
}
catch (Exception ex)
{
return new JsonResult() { Data = Json(new { Success = false, Error = ex.Message }) };
}
}
#endregion
Thanks a lot in advance for your time and help.
Best regards,
Fernando.
I got it. It was a subtle solution, as I barely guessed:
If Javascript is disabled, or in certain circumstances, you need to explicitly pass action to the AjaxOptions, like that:
AjaxOptions ajaxOptions = new AjaxOptions()
{
HttpMethod = "POST",
OnSuccess = "OnSuccess(data)",
OnFailure = "OnFailure",
OnBegin = "OnBegin",
OnComplete = "OnComplete",
Url = Url.Action("GetDialogV2")
};
I am getting error when I click on submit.
Error Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
My view
#model renderview.Models.Registration
<div id="body">
<h2>Contact</h2>
#using (Html.BeginForm("Registration", "home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken() // this is to prevent CSRF attack
#Html.ValidationSummary(true)
<h3>Sign up</h3>
<label for="name">
<span>Name</span>
#Html.TextBoxFor(model => model.Name)
#Html.ValidationMessageFor(model=>model.Name)
</label>
<label for="email">
<span>Email</span>
#Html.TextBoxFor(model => model.Email)
#Html.ValidationMessageFor(model=>model.Email)
</label>
<label for="password">
<span>Pasword</span>
#Html.TextBoxFor(model => model.Password, new { #type = "password" })
#Html.ValidationMessageFor(model => model.Password)
</label>
<label for="Phone">
<span>Phone</span>
#Html.TextBoxFor(model => model.Phone)
#Html.ValidationMessageFor(model => model.Phone)
</label>
<label for="Address">
<span>Address</span>
#Html.TextAreaFor(model => model.Address, new {style ="width: 100"})
#Html.ValidationMessageFor(model => model.Address)
</label>
<p>Select Country:</p>
#Html.DropDownList("Country", ViewBag.country as SelectList,"Select a Country", new { #id="Country"});
<br />
<p>Select State:</p>
<select id="State" name="state"></select><br />
// #Html.DropDownList("State");
<br />
<br />
<input type="file" name="ImageData" id="ImageData" onchange="fileCheck(this);" />
<br />
<input type="submit" id="send" value="Submit">
}
</div>
<script src="~/Scripts/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-1.8.2.js"></script>
<script>
$(document).ready(function () {
$("#Country").change(function () {
var gfhsdf = $("#Country").val();
alert(gfhsdf)
var url="#Url.Action("GetStates1", "home")";
$.ajax({
type: 'GET',
url: url,
data: { id: $("#Country").val() },
success: function (data) {
$.each(data, function (i, state) {
$("#State").append('<option value=" ' + state.Id + ' ">' + state.Name + '</option>');
//alert(st.Id);
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
});
});
</script>
My Controller
public ActionResult Registration()
{
DataClassesRegistrationDataContext db = new DataClassesRegistrationDataContext();
List<CountryModel> Countrydropdownlist = new List<CountryModel>();
var q = (from r in db.Countries select r).ToList();
if (q != null)
{
foreach (var query in q)
{
CountryModel con = new CountryModel();
con.Id = query.Id;
con.Name = query.Name;
Countrydropdownlist.Add(con);
}
ViewBag.country = new SelectList(Countrydropdownlist,"Id","Name");
}
return View();
}
public JsonResult GetStates1(int id)
{
DataClassesRegistrationDataContext db = new DataClassesRegistrationDataContext();
var query = (from s in db.tbl_States
where id==s.CountryId select s).ToList();
return Json(query,JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Registration(Registration _model)
{
HttpPostedFileBase file = Request.Files["ImageData"];
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(
Server.MapPath("~/Content/images/"), pic);
file.SaveAs(path);
_model.Image = pic;
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
} AccountServices service = new AccountServices();
_model.Password = passwordEncrypt(_model.Password);
service.Registration(_model);
return RedirectToAction("index");
}
This error was due to some new properties added in model.
when adding a customer (client) , I have a DropDownList of Number , when I select RaisonSocial should get the value relative to the number :
the Number and RaisonSocial are two attributes in the same table
This is my controller'action :
[HttpGet]
public ActionResult Register()
{
ViewBag.No_ = new SelectList(dbCustomer.AURES_GROS_Customer.ToList(), "No_", "No_");
ApplicationUser user = new ApplicationUser();
// Get Raison Sociale relative to No_ selected
user.RaisonSociale = context.Users.First(c => c.No_.Equals(NumClient)).RaisonSociale;
ViewBag.Remise = user.RaisonSociale;
//ViewBag.Remise= new SelectList(dbCustomer.AURES_GROS_Customer.ToList(), "Name", "Name");
return View();
}
This is my View : // Register :
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal form-label-left", role = "form", #id = "demo-form2" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary("", new { #class = "text-danger" })
#*" Label de Numéro de Client"*#
<div class="form-group">
<label for="No_" class="control-label col-md-3 col-sm-3 col-xs-12">N° Client</label>
<div class="col-md-9 col-sm-9 col-xs-12">
#Html.DropDownList("No_", (SelectList)ViewBag.No_, " -- Selectionner numéro de Client -- ", new { #id="test", onchange = "document.getElementById('NumClient').value = this.value;" })
</div>
</div>
#*" Label de Raison Sociale"*#
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="RaisonSociale">
Raison Sociale
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" name="RaisonSociale" value="#ViewBag.Remise" readonly="readonly" class="form-control col-md-7 col-xs-12" />
</div>
</div>
Thanks
Modify your dropdown onchange function
#Html.DropDownList("No_", (SelectList)ViewBag.No_, " -- Selectionner numéro de Client -- ", new { #id="test", onchange = "getddlVal(this.value)" })
Javascript
function getddlVal(selectedval)
{
window.location = '/Controller/action?ddlvalue=' + selectedval;
}
I have page that uses a partial view for a contact form, and the contact form is validated (so when I don't provide a required field, it redirect me to specific layout I create for this partial.)
Here is how my page is laid out:
Last image is a blank_layout I created for my partial view because if I don't do it, it changes all content like navbar and other parts of the page.
View Model:
public class ContactoViewModel
{
public IEnumerable<ProductosModel> ProductosListes { set; get; }
public String Descripcion { get; set; }
public String Id { get; set; }
[Required(ErrorMessage = "Es necesario que ingrese su nombre")]
public String Name { get; set; }
[Required(ErrorMessage = "Es necesario que ingrese su correo")]
[Email(ErrorMessage = "Ingrese un Email válido")]
public String Email { get; set; }
[Required(ErrorMessage = "Ingrese algún comentario por favor")]
[MinLength(10, ErrorMessage = "Es necesario que ingrese al menos 10 caracteres")]
public String Comments { get; set; }
}
Partial view:
#model DismedHmo.Models.ContactoViewModel
#{
Layout = "~/Views/Shared/Blank_Layout.cshtml";
}
#*<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/component.css" rel="stylesheet" />
<link href="~/Content/default.css" rel="stylesheet" />*#
<div class="row">
<!-- feedback -->
<article class="feedback">
#*<div class="title-contact">Deja un mensaje </div>*#
#using (Html.BeginForm("Contact_Partial", "ContactModels", FormMethod.Post))
{
<div class="title-margin">
#*<h6>Campos Requeridos*</h6>*#
</div>
<div class="input-group">
<div class="col-md-12">
<div class="relative">
<i class=" fa fa-user appointment-contact"></i>
<div class="contactlbl">
#Html.TextBoxFor(model => model.Name, new { #class = "form-control, txtboxexpand", #style = "width:100%", #placeholder = "Nombre*" })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="input-group">
<div class="col-md-12">
<div class="relative">
<i class=" fa fa-envelope appointment-contact"></i>
<div class="contactlbl">
#Html.TextBoxFor(model => model.Email, new { #class = "form-control, txtboxexpand", #style = "width:100%", #placeholder = "Email*", #type = "email" })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="input-group">
<div class="hidden-xs col-sm-12 col-md-12 col-lg-12">
<div class="relative">
<i class=" fa fa-align-left appointment-message"></i>
</div>
<div class="contactlbl">
#Html.TextAreaFor(model => model.Comments, new { #class = "form-control, txtareaexpand", #style = "width:100%", #placeholder = "Mensaje*" })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="input-group">
<div class="col-xs-12 hidden-sm hidden-md hidden-lg">
<div class="relative">
<i class=" fa fa-align-left appointment-message"></i>
</div>
<div class="contactlbl">
#Html.TextAreaFor(model => model.Comments, new { #class = "form-control, txtareaexpandxs", #style = "width:100%", #placeholder = "Mensaje*" })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group margen-btn">
<div class="col-sm-12">
<input type="submit" value="Solicitar cotización" class="btn btn-contacto" />
</div>
</div>
}
</article>
</div>
Calling partial view on main page:
<div class="col-md-6">
#Html.Action("Contact_Partial", "ContactModels")
</div>
Controller:
[HttpPost]
public ActionResult Contact_Partial(ContactoViewModel model)
{
if (!ModelState.IsValid)
{
Danger("Su mensaje no fue enviado, porfavor intente de nuevo.");
return View();
}
using (var emailService = new EmailService())
{
emailService.SetRecipient("contacto#dismedhmo.com");
emailService.Contacto(model.Name, model.Email, model.Comments);
emailService.Send();
}
Success(string.Format("Tu mensaje ha sido enviado con exito."), true);
return RedirectToAction("Productos", "Productos");
}
public ActionResult MensajeEnviado()
{
return View();
}
I really want the validation page to be displayed where the contact form was. How can I do this?
I have a form that was not receiving any of my model information on the postback. I have tried to comment out more and more to make it simple so I can see when it works and so far I am having no luck. I have commented out most of the complex parts of the form and model so I do not know why I am having issues.
Below is the controller functions to show the form and to post it
public ActionResult MassEmail()
{
IEmailTemplateRepository templates = new EmailTemplateRepository();
IEmailFromAddressRepository froms = new EmailFromAddressRepository();
IEmployeeRepository emps = new EmployeeRepository();
List<ProductVersion> vers = new List<ProductVersion>();
MassEmailViewModel vm = new MassEmailViewModel();
vers = productVersionRepository.All.OrderBy(o => o.Description).ToList();
foreach (Employee e in emps.Employees.Where(o => o.Department == "Support" || o.Department == "Professional Services").OrderBy(o => o.Name))
{
if (e.Email != null && e.Email.Trim() != "")
{
vm.BCCAddresses = vm.BCCAddresses + e.Email + ",";
}
}
if (vm.BCCAddresses != "")
{
vm.BCCAddresses = vm.BCCAddresses.Substring(0, vm.BCCAddresses.Length - 1);
}
ViewBag.PossibleCustomers = customerRepository.All.OrderBy(o => o.CustomerName);
ViewBag.PossibleTemplates = templates.All.OrderBy(o => o.Description);
ViewBag.PossibleFromAddresses = froms.All.OrderBy(o => o.Description);
ViewBag.PossibleClasses = scheduledClassRepository.All.OrderByDescending(o => o.ClassDate).ThenBy(o => o.ClassTopic.Description);
vm.CCAddresses = "bclairmont#harrisworld.com";
//vm.Attachments = "";
vm.Body = "";
vm.Subject = "";
vm.ToAddresses = "";
vm.EmailFromAddressID = 1;
return View(vm);
}
[HttpPost]
public ActionResult MassEmail(MassEmailViewModel vm)
{
IEmailFromAddressRepository froms = new EmailFromAddressRepository();
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.From = new System.Net.Mail.MailAddress(froms.Find(vm.EmailFromAddressID).Email);
string[] toAddresses = vm.ToAddresses.Split(',');
for (int i = 0; i < toAddresses.GetUpperBound(0); i++)
{
message.To.Add(new System.Net.Mail.MailAddress(toAddresses[i]));
}
string[] CCAddresses = vm.CCAddresses.Split(',');
for (int i = 0; i < CCAddresses.GetUpperBound(0); i++)
{
message.To.Add(new System.Net.Mail.MailAddress(CCAddresses[i]));
}
string[] BCCAddresses = vm.BCCAddresses.Split(',');
for (int i = 0; i < BCCAddresses.GetUpperBound(0); i++)
{
message.To.Add(new System.Net.Mail.MailAddress(BCCAddresses[i]));
}
message.IsBodyHtml = true;
message.BodyEncoding = Encoding.UTF8;
message.Subject = vm.Subject;
message.Body = vm.Body;
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFileBase file = Request.Files[i];
message.Attachments.Add(new Attachment(file.InputStream, file.FileName));
}
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
client.Send(message);
return RedirectToAction("MassEmail");
}
Next is the code for my View
#model TRIOSoftware.WebUI.Models.MassEmailViewModel
#{
ViewBag.Title = "MassEmail";
}
#using (Html.BeginForm())
{
<h1 class="align-right">Mass E-Mail</h1>
<br />
<br />
<div>
<div class="editor-label" style="float:left; width:90px">
From
</div>
<div class="editor-field" style="float:left">
#Html.DropDownListFor(model => model.EmailFromAddressID,
((IEnumerable<TRIOSoftware.Domain.Entities.EmailFromAddress>)
ViewBag.PossibleFromAddresses).OrderBy(m => m.Description).Select(option => new
SelectListItem
{
Text = option.Description.ToString(),
Value = option.ID.ToString(),
Selected = (Model != null) && (option.ID == Model.EmailFromAddressID)
}), "Choose...")
</div>
</div>
<div class= "TagitEmailAddress" style="width:100%">
<div class="editor-label" style="float:left; clear:left; width:90px">
To
</div>
<div class="editor-field" style="float:left; width:88%">
#Html.TextBoxFor(model => model.ToAddresses, new { #class = "TagTextBox" })
</div>
</div>
<div class= "TagitEmailAddress" style="width:100%">
<div class="editor-label" style="float:left; clear:left; width:90px">
CC
</div>
<div class="editor-field" style="float:left; width:88%">
#Html.TextBoxFor(model => model.CCAddresses, new { #class = "TagTextBox" })
</div>
</div>
<div class= "TagitEmailAddress" style="width:100%">
<div class="editor-label" style="float:left; clear:left; width:90px">
<input type="button" id="BCC" value="BCC" class="btn"/>
</div>
<div class="editor-field" style="float:left; width:88%">
#Html.TextBoxFor(model => model.BCCAddresses, new { #class = "TagTextBox" })
</div>
</div>
<div style="width:100%">
<div style="float:left; clear:left; width:90px">
<input type="button" id="Subject" value="Subject" class="btn"/>
</div>
<div style="float:left; width:88%">
#Html.TextBoxFor(model => model.Subject, new { id = "SubjectText", style =
"width:100%" })
</div>
</div>
<div style="width:100%">
<div style="clear:left; float:left; width:100%;">
<div class="editor-field" style="float:left; width:100%;">
#Html.TextAreaFor(model => model.Body, new { id = "BodyText" })
</div>
</div>
</div>
<br />
<br />
<br />
<p style="clear:both">
<input type="submit" value="Send E-Mail" class="btn btn-primary"/>
</p>
<div id="DefaultEmailText">
<div class="editor-label" style="float:left; width:150px">
E-Mail Template
</div>
<div class="editor-field" style="float:left; padding-left:10px">
#Html.DropDownList("EmailTemplate",
((IEnumerable<TRIOSoftware.Domain.Entities.EmailTemplate>)
ViewBag.PossibleTemplates).Select(option => new SelectListItem
{
Text = option.Description,
Value = option.ID.ToString(),
Selected = false
}), "Choose...", new { ID = "Template", style = "width:200px" })
</div>
</div>
}
#section sidemenu {
#Html.Action("EmailsSideMenu", "Admin")
}
<script type="text/javascript">
var TemplateSubject = "";
var TemplateBody = "";
$(document).ready(function () {
$('#attach').MultiFile({
STRING: {
remove: '<i style="color:Red" class="icon-remove-sign"></i>'
}
});
$(".TagTextBox").tagit();
$("#BodyText").cleditor({
width: 800,
height: 400
});
$("#DefaultEmailText").dialog({
autoOpen: false,
height: 150,
width: 250,
title: "Default Subject / Body",
modal: true,
buttons: {
OK: function () {
var selectedTemplate = $("#DefaultEmailText #Template").val();
if (selectedTemplate != null && selectedTemplate != '') {
$.getJSON('#Url.Action("GetTemplate", "EmailTemplates")', { id:
selectedTemplate }, function (template) {
$("#SubjectText").val(template[0].Subject);
$("#BodyText").val(template[0].Body).blur();
});
}
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$('#Subject').click(function () {
$("#DefaultEmailText").dialog("open");
});
});
</script>
When I submit I get all null values except for the EmailFromAddressID which is 0 even though ti gets defaulted ot 1 when the view loads.
Any ideas?
EDIT____________________________________
I looked in DevConsole of Chrome and under network I coudl see my post request. Below is the detailed informaiton it contained. It looks to me liek the data did get sent to the server so I do not knwo why the server cant fill in my Model class
Request URL:http://localhost:53730/Customers/MassEmail
Request Headersview source
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Content-Type:application/x-www-form-urlencoded
Origin:http://localhost:53730
Referer:http://localhost:53730/Customers/MassEmail
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko)
Chrome/24.0.1312.52 Safari/537.17
Form Dataview sourceview URL encoded
EmailFromAddressID:1
ToAddresses:
CCAddresses:bclairmont#harrisworld.com
BCCAddresses:adunn#harrisworld.com,bclairmont#harrisworld.com,
bkelly#harrisworld.com,bhackett#harrisworld.com,jwade#harrisworld.com,
krichter#harrisworld.com,mroy-waters#harrisworld.com,
nburckhard#harrisworld.com,rlibby#harrisworld.com
Subject:Testing
Body:
Here is the class that gets passed back and forth from the clien tto server in case that helps
public class MassEmailViewModel
{
//public MassEmailViewModel()
//{
// ComplexQuery = new CustomerQueryViewModel();
//}
public int EmailFromAddressID;
// public CustomerQueryViewModel ComplexQuery;
public string ToAddresses;
public string CCAddresses;
public string BCCAddresses;
public string Subject;
public string Body;
//public string Attachments;
}
The DefaultModelBinder needs public properties not public fields.
Change your fields to properties and it should work:
public class MassEmailViewModel
{
public int EmailFromAddressID { get; set; }
public string ToAddresses { get; set; }
public string CCAddresses { get; set; }
public string BCCAddresses { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
}
1) Have you tried specifing the route of the controller to which the model will be submited?. I mean, declaring the form like this:
#using (Html.BeginForm("YourAction","YourController", FormMethod.Post))
2) Why dont you just create a simple "Get" action that returns the strongly typed view and a "Post" action that receives the same model with the information you added in the view. Once you make work that, you can begin adding extra code so it is easy to trobleshoot the problem.
3) Make sure all of your helpers are inside the form.
4) Have you configured routing rules that can be making your post being redirected to another area, controller or action?