Unable to use telerik notification in asp.net mvc project - asp.net-mvc

I would like to use noty in my Asp.net Mvc project, however since I can not do it, I prefer telerik aversely. The algorithm is, user registers a web page,processes at the server side, in case of success I would like to show a message at the client. Here is the usage of telerik notification:
http://demos.telerik.com/aspnet-mvc/notification/index
here is my source: (HomeController/Register)
[HttpPost]
public ActionResult Register(Users user)
{
IAraclar tool = null;
string uname = null;
IKisiBL userBusinessRule = null;
try
{
tool = new toollar();
uname = tool.GetUserName(user.UserEmail);
user.UserName = uname;
USERS newDataUser = new USERS
{
USER_ID = 0,
USER_EMAIL = user.UserEmail,
USER_NAME = user.UserName,
USER_PASSWORD = user.UserPassword,
USER_ROLE_TIP = (short)user.UserRoleTipi,
USER_KURUM_TIPI = (short)user.UserKurumTipi
};
using (LojmanEntities entities = new LojmanEntities())
{
entities.USERS.Add(newDataUser);
entities.SaveChanges();
}
}
catch (Exception ex)
{
tool.HataRaporla(ex);
throw;
}
//ViewData["SuccessMessage"] = SistemMesajlari.KayitTamamlandi_ok();
return View();
}
https://docs.google.com/document/d/11EoaOQysDa0FmNIawSZ1AafOh0pZ58W_Qku2Z3BnXWo/edit?usp=sharing
Here is my Register.cshtml, in which tightly coupled with the Action above :
#model LojmanMVC.Domain.Entities.Users
#{
ViewBag.Title = "Lojman Bilgi Sistemi Kullanıcı Kaydı";
}
<h2>Lojman Bilgi Sistemi Kullanıcı Kaydı</h2>
<p id="sifresonuc"> </p>
#*prospective item that shows message*#
#(Html.Kendo().Notification()
.Name("staticNotification")
.AppendTo("#appendto")
)
#*classical form in mvc*#
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Lütfen kullanıcı bilgilerinizi giriniz: </legend>
<div class="editor-label">
#Html.LabelFor(model => model.UserEmail) (Bakanlıkça verilen e-posta adresiniz)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserEmail)
#Html.ValidationMessageFor(model => model.UserEmail)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.UserPassword)
</div>
<div class="editor-field">
#Html.TextBoxFor(item => item.UserPassword, new { id = "password1" })
</div>
<div class="editor-label">
<label for="male">Lütfen şifrenizi tekrar giriniz: </label>
</div>
<div class="editor-field">
<input type="password" name="password2" id="password2" />
</div>
<div class="editor-label">
<label for="male">Lütfen rolünüzü giriniz: </label>
</div>
<div class="editor-field">
#Html.MyEnumDropDownListFor(m => m.UserRoleTipi)
</div>
<p>
<input type="submit" id="registerButton" value="Kayıt Ol" />
</p>
<button id="showStaticNotification" class="k-button">Static in the panel below</button>
</fieldset>
}
<script type="text/javascript">
console.log("1");
function checkPasswordMatch() {
console.log("checkPasswordMatch");
var password = $("#password1").val();
var confirmPassword = $("#password2").val();
if (password != confirmPassword) {
$("#sifresonuc").html("Şifreler uyuşmamaktadır!");
var $p = $("#sifresonuc");
var $button = $("#registerButton");
$button.prop('disabled', true);
$p.css("background-color", "red").show(500);
}
else {
$("#sifresonuc").html("");
var $p = $("#sifresonuc");
$p.css("background-color", "white").show(500);
var $button = $("#registerButton");
$button.prop('disabled', false);
}
}
console.log("2");
$(document).ready(function () {
$("#password2").keyup(checkPasswordMatch);
});
console.log("3");
function InputToLower(obj) {
if (obj.value != "") {
obj.value = obj.value.replace('İ', 'i').replace('I', 'ı').toLowerCase();
}
}
console.log("4");
$(function () {
$("#registerButton").click(function (e) {
console.log("5");
// e.preventDefault();
var errorSummary = $('.validation-summary-errors');
console.log("6");
if (errorSummary.length == 0) {
$('#listError').remove();
$('<div class="validation-summary-errors"></div>').insertAfter($('.validation-summary-valid'));
$(".validation-summary-errors").append("<ul id='listError'><li>0 karakter giremezsiniz. OSI-122 </li></ul>");
}
else if (errorSummary.length == 1) {
$('#listError').remove();
$(".validation-summary-errors").append("<ul id='listError'><li>You cannot enter more than 20 characters.</li></ul>");
}
//return false;
// place that sets notification
console.log("7");
var d = new Date();
staticNotification.show(kendo.toString(d, 'HH:MM:ss.') + kendo.toString(d.getMilliseconds(), "000"), "info");
var container = $(staticNotification.options.appendTo);
container.scrollTop(container[0].scrollHeight);
console.log("8");
});
});
</script>
https://docs.google.com/document/d/1t7g9K4v5BrIyFkHVCMxVowDUbMlT3P6Tsz-88d7YOuA/edit?usp=sharing
(Since I can not write these lines of code despite every efforts, I share it via google docs)
When I run the code, there is no notification appear in the page, and "1,2,3,4" was appeared at the console.Function contains 5 does not work there. What things did I do wrong?
Thanks in advance.

I think you should try to assign the handler of your registerButton in the $document.ready() function, and try to assign the handler of the click event using the functions unbind/bind.
document.ready(function(){
$("#registerButton").unbind("click").bind("click", function() {
<your code here>
...
});
});

Related

Ajax begin form db record with mvc

I created a form. I want to do a post save method.
He records but records the same data twice. How can I solve this problem?
I have to solve the double registration problem. I'm pushing the button once. When I go through Debug step by step, it goes twice on the same line. When I control the db as a top-down, I see that you double-logged.
HTML:
<div class="portlet-body form">
#using (Ajax.BeginForm("TalepTurKaydet", "MasterEducationController",
new AjaxOptions { HttpMethod = "post", OnSuccess = "TalepTurKaydet" },
new { #class = "" }))
{
#Html.ValidationSummary(true)
<div class="form-body">
<div class="row">
<div class="col-md-12" style="margin-left: 20px">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Açıklama: </label>
<div class="col-md-9">
<textarea id="Aciklama" name="Aciklama" class="col-md-12" style="resize: none;" rows="5" placeholder="Açıklama"></textarea>
</div>
</div>
</div>
<div class="clearfix"></div><br /><br />
</div>
<div class=" form-actions right">
<button type="button" class="btn green btnPrevious"><i class="fa fa-angle-double-left"></i>Geri</button>
<button id="talepOlustur" type="submit" class="btn blue"><i class="fa fa-check"></i> Talep Oluştur</button>
</div>
</div>
}
</div>
Controller:
public ActionResult MezuniyetBilgiKaydet(MezuniyetBilgi model)
{
List<MezuniyetBilgi> list = null;
model.KullaniciId = GetUye().kullaniciID;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ApiAdress.API_URL);
var responseTask = client.PostAsJsonAsync("apiMasterProgramEducation/MezuniyetBilgiKaydet", model);
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<List<MezuniyetBilgi>>();
readTask.Wait();
list = readTask.Result;
model = list.FirstOrDefault();
return Json(new
{
Success = true,
data = model,
Message = SuccessMessage.MEZUNIYET_BILGISI_INSERT_MESSAGE,
JsonRequestBehavior.AllowGet
});
}
}
}
API:
public IHttpActionResult MezuniyetBilgiKaydet(MezuniyetBilgi model)
{
List<MezuniyetBilgi> detay = new List<MezuniyetBilgi>();
try
{
using (var ctx = new ktdbEntities())
{
if (model != null)
{
var query = ctx.mezuniyetBilgisiEkle(model.KullaniciId, model.MezuniyetTarih, model.MezunOlduguOkul,
model.MezunOlduguFakulte, model.MezunOlduguBolum, (float)(model.MezuniyetNotu));
model.Output = true;
detay.Add(model);
return Ok(detay);
}
}
}
catch (Exception e)
{
model.Output = false;
model.Message = e.Message;
detay.Add(model);
}
return Ok(detay);
}

ASP.NET MVC return 500 for dropdownlist cascading

Am using it for cascading dropdownlist for country and state. When I click on
country dropdownlist that suppose to display states, I got 500 server error. Please help me
The error occurs when I click the Country dropdownlist
[HttpPost]
[ValidateAntiForgeryToken] //this is to prevent CSRF attack
public ActionResult Create(CITIES ci)
{
List<COUNTRIES> allCountry = new List<COUNTRIES>();
List<STATES> allState = new List<STATES>();
using (AdminEntities dc = new AdminEntities())
{
allCountry = dc.COUNTRIES.OrderBy(a => a.COUNTRY_NAME).ToList();
if (ci != null && ci.COUNTRY_ID > 0)
{
allState = dc.STATES.Where(a => a.COUNTRY_ID.Equals(ci.COUNTRY_ID)).OrderBy(a => a.STATE_NAME).ToList();
}
}
ViewBag.COUNTRY_ID = new SelectList(allCountry, "COUNTRY_ID", "COUNTRY_NAME", ci.COUNTRY_ID);
ViewBag.STATE_ID = new SelectList(allState, "STATE_ID", "STATE_NAME", ci.STATE_ID);
if (ModelState.IsValid)
{
using (AdminEntities dc = new AdminEntities())
{
dc.CITIES.Add(ci);
dc.SaveChanges();
ModelState.Clear();
ci = null;
ViewBag.Message = "Successfully Saved";
}
}
else
{
ViewBag.Message = "Failed! Please try again";
}
return View(ci);
}
[HttpGet]
public JsonResult GetStates(string countryID = "")
{
// List<COUNTRIES> allCountry = new List<COUNTRIES>();
List<STATES> allState = new List<STATES>();
int ID = 0;
if (int.TryParse(countryID, out ID))
{
using (AdminEntities dc = new AdminEntities())
{
allState = dc.STATES.Where(a => a.COUNTRY_ID.Equals(ID)).OrderBy(a => a.STATE_NAME).ToList();
}
}
if (Request.IsAjaxRequest())
{
return new JsonResult
{
Data = allState,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
else
{
return new JsonResult
{
Data = "Not valid request",
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}
view
#model BPP.CCSP.Admin.Web.Models.CITIES
Create
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="form-horizontal">
<h4>CITIES</h4>
<hr />
#if(ViewBag.message != true)
{
<div style="border:solid 1px black">
#ViewBag.message
</div>
}
<div class="form-group">
#Html.LabelFor(model => model.COUNTRY_ID, "COUNTRY_ID", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#* #Html.DropDownListFor(model=>model.COUNTRY_ID, new SelectList(string.Empty, "Value", "Text"), "Please select a country", new { #style = "width:250px;" }) *#
#Html.DropDownListFor(model => model.COUNTRY_ID, #ViewBag.COUNTRY_ID as SelectList,"Select Country")
#Html.ValidationMessageFor(model => model.COUNTRY_ID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.STATE_ID, "STATE_ID", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#* #Html.DropDownListFor(model => model.STATE_ID, new SelectList(string.Empty, "Value", "Text"), "Please select a state", new { #style = "width:250px;" }) *#
#Html.DropDownListFor(model => model.STATE_ID, #ViewBag.STATE_ID as SelectList, "Select State")
#Html.ValidationMessageFor(model => model.STATE_ID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CITY_NAME, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CITY_NAME)
#Html.ValidationMessageFor(model => model.CITY_NAME)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script language="javascript">
$(document).ready(function () {
$("#COUNTRY_ID").change(function () {
//this will call when country dropdown select change
var countryID = parseInt($("#COUNTRY_ID").val());
if (!isNaN(countryID))
{
var ddState = $("#STATE_ID");
ddState.empty(); //this line is to clear all items from statee dropdown
ddState.append($("<option></option>").val("").html("Select State"));
//here i will call controller action via jquery to load state for selected country
$.ajax({
url: "#Url.Action("GetStates","CITIES")",
type: "GET",
data: {countryID : countryID},
dataType: "json",
success: function (data)
{
$.each(data, function (i, val) {
ddState.append(
$("<option></option>").val(val.STATE_ID).html(val.STATE_NAME)
);
});
}
,
error: function ()
{
alert("Error!");
}
});
}
});
});
</script>
}
Please what do I do
can you try
var data = {"countryID" : countryID};
$.ajax({
url: '#Url.Content("~/CITIES/GetStates")',
type: "GET",
contentType: 'application/json',
data:JSON.stringify(data),
});
and then debug GetStates action and if you get error there you will get normally 500 server error

Html.ValidationMessageFor() not rendering <span> element

I've been using Html.ValidationMessageFor for quite a long time in MVC 3. All of a sudden this extension is no longer working for me, but only in a particular view. The extension is used in a <form> tag and the page has the jquery.validate.min.js and jquery.validate.unobtrusive.min.js attached (among others). I've checked other pages of the site, and those views use the same call and the <span> element is generated.
Here is the markup I'm using:
<form id="assistanceRequestDiv" class="form-group js-more-assistance js-hidden">
<p>#Translation.TextByDomain("Assistance", "need-further-assistance-contact-customer-support")</p>
<div class="content-block left-text-children">
<div class="content-block__quarter-column">
#Html.LabelFor(x => x.AssistanceRequestFirstName)
#Html.ValidationMessageFor(x => x.AssistanceRequestFirstName)
#Html.TextBoxFor(x => x.AssistanceRequestFirstName, new {#class = "form-control", required = "required"})
</div>
<div class="content-block__quarter-column">
#Html.LabelFor(x => x.AssistanceRequestLastName)
#Html.ValidationMessageFor(x => x.AssistanceRequestLastName)
#Html.TextBoxFor(x => x.AssistanceRequestLastName, new {#class = "form-control", required = "required"})
</div>
<div class="content-block__quarter-column">
#Html.LabelFor(x => x.AssistanceRequestPhoneNumber)
#Html.ValidationMessageFor(x => x.AssistanceRequestPhoneNumber)
#Html.TextBoxFor(x => x.AssistanceRequestPhoneNumber, new {#class = "form-control"})
</div>
<div class="content-block__quarter-column set-vertical-align-bottom">
<button id="btnSubmitAssistanceRequest" class="btn btn--primary">#Translation.Text("submit")</button>
</div>
</div>
</form>
Data Annotations
[RequiredLocalized, DisplayNameLocalized("first-name")]
public string AssistanceRequestFirstName { get; set; }
[RequiredLocalized, DisplayNameLocalized("last-name")]
public string AssistanceRequestLastName { get; set; }
[RequiredLocalized, DisplayNameLocalized("phone-required")]
[RegularExpressionLocalized(#"(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]‌​)\s*)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)([2-9]1[02-9]‌​|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})", "please-enter-a-valid-10-digit-phone-number", "Assistance")]
public string AssistanceRequestPhoneNumber { get; set; }
RequiredLocalized - Required attribute that returns a custom message. Works in other places of the site.
DisplayNameLocalized - DisplayName attribute with custom message. Works in other places.
Etc
This form is hidden by default and shown when the user clicks a certain button. Here are the scripts that are attached to the page:
<script src="/Scripts/jquery-1.8.3.min.js"></script>
<script src="/Scripts/jquery-ui-1.10.4.custom.min.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="/Scripts/jquery.validate.min.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="/Scripts/jquery.validate.extensions.js"></script>
<script src="/Scripts/Shared/jQueryGlobalSettings.js"></script>
Using Javascript to return false if there are errors on the page in this format:
$('#btnSubmitAssistanceRequest').click(function (e) {
var $answer = $('.js-title');
var $reqFirstName = $('#AssistanceRequestFirstName');
var $reqLastName = $('#AssistanceRequestLastName');
var $reqPhoneNumber = $('#AssistanceRequestPhoneNumber');
// Check for empty fields
if ($reqFirstName.val().trim() == "") {
showErrorMessage($reqFirstName, 'First Name is required.');
} else {
clearErrorMessage($reqFirstName);
}
if ($reqLastName.val().trim() == "") {
showErrorMessage($reqLastName, 'Last Name is required.');
} else {
clearErrorMessage($reqLastName);
}
if ($reqPhoneNumber.val().trim() == "") {
showErrorMessage($reqPhoneNumber, 'Phone Number is required.');
} else {
clearErrorMessage($reqPhoneNumber);
}
// check if validation errors were thrown
if ($(".field-validation-error").length) return false;
$.post('/api/[obfuscated]/[obfuscated]', { answer: $answer.text(), firstName: $reqFirstName.val(), lastName: $reqLastName.val(), phoneNumber: $reqPhoneNumber.val() }, function (data) {
if (data.success) {
$('.request-assistance-success').css('display', 'inline');
$(".feedback-container").slideUp(400);
} else {
$('.request-assistance-failure').css('display', 'inline');
$(".feedback-container").slideUp(400);
}
});
e.preventDefault();
return true;
});
Replace
<button id="btnSubmitAssistanceRequest" class="btn btn--primary">#Translation.Text("submit")</button>
with
<input type="submit" id="btnSubmitAssistanceRequest" class="btn btn--primary" Text="#Translation.Text("submit")"/>
Submit form invokes the unobtrusive validations.

Getting error: An item with the same key has already been added

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.

Postback Contains No Model Data

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?

Resources