Chat using signalR in asp.net mvc - asp.net-mvc

I am trying to make a chat application using SignalR wherein the user can chat with other users in a private box. Everything works fine except for the fact that the client and the user chats are displayed on the same side and work fine when refreshed.
Here's my code for the Same:
public class ChatHub : Hub
{
static List<ConnectedUser> objConnectedUserList = new List<ConnectedUser>();
MessagingDAL objMessagingDAL = new MessagingDAL();
NurseDAL objNurseDAL = new NurseDAL();
public void SendPrivateMessage(Messaging objMessaging)
{
var fromNurse = objConnectedUserList.FirstOrDefault(x => x.NurseId == objMessaging.FromNurseId);
var toNurse = objConnectedUserList.FirstOrDefault(x => x.NurseId == objMessaging.ToNurseId);
var chatObject = new { MessageThreadId = 0, Name = fromNurse.NurseName, Message = objMessaging.Message, DTStmp = DateTime.Now, frmNurseId = fromNurse.NurseId };
Result objResult = objMessagingDAL.InsertMessage(objMessaging);
if (toNurse != null)
{
Clients.Client(toNurse.ConnectionId).ReceivePrivateMessage(chatObject);
}
Clients.Caller.ReceivePrivateMessage(chatObject);
}
}
}
Here's my code for Controller:
$scope.SendPrivateMessage = function (message) {
if ($scope.Thread.MessageThreadId == null) {
UserService.showAlert('Please select a Nurse', 0);
return;
}
else {
var chatObject =
{
MessagingThreadId: $scope.Thread.MessageThreadId,
Message: message,
ToRecruiter: null,
ToRecruiterId: null,
FromRecruiter: null,
FromRecruiterId: null,
ToNurse: null,
ToNurseId: $scope.Thread.ToNurseId,
FromNurse: null,
FromNurseId: $scope.Thread.FromNurseId,
CreatedOn: new Date(),
RecivedOn: new Date(),
LastMessageOn: new Date(),
}
}
signalR.SendPrivateMessage(chatObject);
$scope.Messaging.Message = '';
$scope.Init(chatObject.Message);
}
signalR.ReceivePrivateMessage(function (chatObject) {
$scope.Messages.push(chatObject);
//$scope.Messages.push({ chatObject });
$("#autoscroll").animate({ scrollTop: $("#autoscroll")[0].scrollHeight * 2 }, 100);
$scope.$apply();
$scope.Init(chatObject.Message);
});
Following is my code for the HTML Page:
<div class="chat_container no-margin no-padding">
<div class="no-margin no-padding MsgRightPnlHdr">
<span class="chatNameRight" ng-bind="Thread.Name"></span>
<span class="chatNameDesigRight" ng-bind="Thread.Designation"></span>
</div>
<div class="userTyping">
<span class="chatNameDesigRight" ng-bind=usertyping></span>
</div>
<div class="no-margin no-padding msgDsplyPnl message-right" id="autoscroll">
<div ng-repeat="msg in Messages" ng-if="msg.Message">
<div class="no-margin no-padding imgDiv1" ng-if="msg.Type=='in'">
<img src="#baseUrl{{Thread.img}}" class="img-responsive" />
</div>
<span class="{{msg.Type=='in'?'pull-left lt-box inMsg':'pull-left rt-box outMsg'}}">{{msg.Message}}<br />
<span class="chatLstDTstmp message-time">{{msg.DTStmp | date:'dd MMM, yyyy hh:mm a'}}</span>
</span>
</div>
</div>
<div class="form-group no-margin no-padding">
<div class="no-margin no-padding">
<textarea name="Message" class="form-control txt-area" style="height:36px; margin-bottom: 10px; resize:none;"
placeholder="Type your Message here..." ng-model="Messaging.Message" ng-keypress="SkeyPress($event)"></textarea>
</div>
<div class="no-margin no-padding">
<button class="btn sendBtn ms-btn" style="width: 100%;height: 60px;border-radius: 0;" ng-click="SendPrivateMessage(Messaging.Message);" ng-disabled="!Messaging.Message">
Send
</button>
</div>
</div>
</div>
Also, the CSS is fine as once the page is refreshed, the chat goes to its respective sides.
Attached image for reference:
Error I am facing

Try this in your ReceivePrivateMessage in app.js:
chatObject.Type = ($scope.UserId == chatObject.frmNurseId ? "out" : "in");

As I've understood is that the position of the message from the other user is not correct?
You're doing the formatting based on the message type: msg.Type='in'
<span class="{{msg.Type=='in'?'pull-left lt-box inMsg':'pull-left rt-box outMsg'}}">{{msg.Message}}<br />
I do not see where do you declare the type of the message, and what does the function $scope.Init(message) actually do?
Also on the hub you do send same message to the caller and the client and what I think is wrong is that they get message with same type, which should not be the case.
What should you do there (at the Hub class) is set message type 'in' for caller, 'out' for client (or vise versa, as you prefer) and in that case the rendering should be fine.
Example:
public void SendPrivateMessage(Messaging objMessaging)
{
var fromNurse = objConnectedUserList.FirstOrDefault(x => x.NurseId == objMessaging.FromNurseId);
var toNurse = objConnectedUserList.FirstOrDefault(x => x.NurseId == objMessaging.ToNurseId);
var chatObject = new { MessageThreadId = 0, Name = fromNurse.NurseName, Message = objMessaging.Message, DTStmp = DateTime.Now, frmNurseId = fromNurse.NurseId };
Result objResult = objMessagingDAL.InsertMessage(objMessaging);
if (toNurse != null)
{
chatObject.Type = "in"; //set different type for receiver and sender
Clients.Client(toNurse.ConnectionId).ReceivePrivateMessage(chatObject);
}
chatObject.Type = "out";
Clients.Caller.ReceivePrivateMessage(chatObject);
}

Related

How to perform a login identification process in the best way?

I have 2 inputs boxes: Public key (user name) and Private key (password). Also I have a hidden warning label.
This is my code (and it's perfectly working ):
<script language="javascript">
function SendLoginData() {
document.getElementById("LoginErrorLabel").style.display = "none";
var url = "/DappAccount/CheckAccount";
$.post(url, { PublicKey: $("#public_key_input").val(), PrivateKey: $("#private_key_input").val() }, function (data) {
if (data == false) {
document.getElementById("LoginErrorLabel").style.display = "block";
return;
}
else {
document.getElementById("loader").style.display = "block";
$("#myform").submit()
}
});
}
</script>
<div class="container">
#using (Html.BeginForm("AccountMainPage", "DappAccount", FormMethod.Post, new { #id = "myform" }))
{
<div class="row justify-content-center">
#Html.TextBoxFor(m => m.publicKey, new { id = "public_key_input", placeholder = "Ethereum Public Key", required = "required" })
</div> <br />
<div class="row justify-content-center">
#Html.TextBoxFor(m => m.privateKey, new { id = "private_key_input", placeholder = "Ethereum Private Key", required = "required", type = "password" })
</div> <br />
<div class="row justify-content-center">
<img id="loader" style="display: none;" src="https://s5.gifyu.com/images/Loader5a73d3b26568dbc4.gif" alt="Loader5a73d3b26568dbc4.gif" border="0" />
</div> <br />
}
<div class="row justify-content-center">
<input id="submit" type="button" value="Login" class="btn btn-primary" onclick="SendLoginData()" />
</div>
<label id="LoginErrorLabel" style="color: red; display: none;">*Wrong login detail !</label>
</div>
What I'm doing here is:
1) Send username&password to the 'CheckAccount' method in the controller, the method returns true/false.
2) If false, show label,
if true, show gif image and send again the details to ActionResult (=AccountMainPage) which returns a new view.
I just wonder, is there a better/shorter way to do it using one post or one method? I heard something about the partial views in MVC, no idea what to do with it. People told me that what I did here is too old for MVC

resource cannot be found for calling back to HttpPost method

I have an MVC project. My site connect to bank gateway and after successfull payment, the results POST to my website to run VerifyPayment method (this method is of type HttpPost).
[HttpPost]
// [AllowAnonymous]
public ActionResult VerifyPayment( VerifyResult Vresult )
{
try
{
// var transact = Request.Form["transId"];
// TempData["msg"] = $"<script>alert('transaction id is: {transact}');</script>";
//// for test
// return View(new VerifyResult() { success = true, SuccessMessage = "nice", Amount = "20000" });
if ( !string.IsNullOrEmpty(Request.Form["transId"]) )
{
Payment ob = new Payment();
string result = ob.verify(Request.Form["transId"].ToString());
JsonParameters Parmeters = JsonConvert.DeserializeObject<JsonParameters>(result);
if ( Parmeters.status == 1 )
{
var userId = User.Identity.GetUserId();
var user = db.Users.Where(u => u.Id == userId).FirstOrDefault();
user.SuccessfullPayment = true;
user.FactorNo = User.Identity.GetUserId();
user.TraceNo = Request.Form["traceNumber"];
user.TransId = int.Parse(Request.Form["transId"]);
user.CardNo = Request.Form["cardNumber"];
user.PurchasedDate = DateTime.Now;
user.State = Parmeters.status;
user.Message = Request.Form["message"];
db.Entry(user).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
Vresult.success = true;
Vresult.TransActionID += Request.Form["transId"].ToString();
Vresult.Amount += Parmeters.amount.ToString();
Vresult.SuccessMessage = "پرداخت با موفقیت انجام شد.";
return RedirectToAction("Index", "DownloadEbook");
}
else
{
Vresult.error = true;
Vresult.ErrorMessage = "کدخطا : " + Parmeters.errorCode + "<br />" + "پیغام خطا : " + Parmeters.errorMessage;
}
}
}
catch ( Exception )
{
Vresult.error = true;
Vresult.ErrorMessage = "متاسفانه پرداخت ناموفق بوده است.";
}
return View(new AllNeededModels() { VerifyResult = Vresult });
}
VerifyPayment method has its own View.cshtml file called "VerifyPayment.cshtml".
#model Mahdavimanesh.Models.AllNeededModels
#{
ViewBag.Title = " ";
}
<div class="container">
#if (Model.VerifyResult.success)
{
<div class="row" style="margin-top: 50px;">
<div class="col-lg-6 center-block" style="float: none;">
<div class="alert alert-success">
<asp:Label ID="lblSuccess" runat="server" ForeColor="Green"
Text=""></asp:Label>
#Model.VerifyResult.SuccessMessage
<br />
: #Model.VerifyResult.TransActionID
<br />
: #(Model.VerifyResult.Amount)
</div>
</div>
</div>
}
else
{
<div class="row" style="margin-top: 50px;">
<div class="col-lg-6 center-block" style="float: none;">
<div class="alert alert-danger">
#Model.VerifyResult.ErrorMessage
</div>
</div>
</div>
}
</div>
Everything works correctly on my localhost. However, when I publish the website, after successful payment and calling back to my website, it notifies me the error of "Resource Cannot be Found". I think the problem is raised because of HttpPost VerifyMethod, and that VerifyPayment.cshtml is for HttpGet method. if this, why it works on my local machine?
Is there any clue?

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

Unable to use telerik notification in asp.net mvc project

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

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