Render message after Ajax post from partial view - c#

I have a partail view that opens in fancybox. When i post the form i want to display a validationmessage in the partial view that shall be open in fancybox.
When i use my code i dont get the alert message and i get redirected to: http://domain.com/TextMessage does anyone know wye ?
The page i get redirected to doesent show it in fancybox, do i need to call it again on success?
_SendSms
$('#sendBtn').click(function () {
var dataArray = $('form').serializeArray();
var dataObj = {};
for (var i = 0; i < dataArray.length; i++) {
dataObj[dataArray[i].name] = dataArray[i].value;
}
$.ajax({
type: "POST",
url: "/TextMessage/Send",
data: AddAntiForgeryToken({ salonId: dataObj['SalonId'], toNumber: dataObj['ToNumber'], message: dataObj['Message'] }),
success: function (respons) {
// Can't reach.
alert("klar");
}
});
});
});
Render Form View:
public PartialViewResult Index()
{
var salon = _customerManager.GetSalon();
var smsViewModel = new SmsViewModel
{
ToNumber = salon.MobileTel,
Message = string.Format("Ni kommer vid första uppstarten av extreme bli frågade om uppgifter. \n Dessa kommer här: \n Databas: {0}.", salon.DatabaseName),
DateSent = DateTime.MinValue,
SentByUser = _securityManager.CurrentUser.Name,
SalonId = salon.Id
};
return PartialView("Partial_Views/_SendSms", smsViewModel);
}
Send method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Send(string salonId, string toNumber, string message)
{
var returnValue = false;
try
{
using (var client = new SmsService.SMSServiceSoapClient("SMSServiceSoap"))
{
//client.SendSMSGeneric(int.Parse(salonId), "Itsperfect Software Europe AB", toNumber, message, 8);
}
returnValue = true;
}
catch (Exception ex)
{
Log.Error("Error trying to get Salons withId", ex);
returnValue = false;
}
return Json(new { success = returnValue }, JsonRequestBehavior.AllowGet);
}
AddAntiforgeryToken function:
function AddAntiForgeryToken(data) {
data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
return data;
};

Because you did not suppress default behavior of the button:
$('#sendBtn').click(function (e) {
e.preventDefault();
// rest of the handler here
}

Related

How to handle jquery array for an asp.net mail list?

I've been struggling about this over two days finding solution. I have form, with inputs, selects and multiple select (email adressess) form is parsed by ajax call to controller, saved to DB and then is email sended. What i need to do is use the list of email adressess from multiple select as an list for mail function. I can't find a suitable method to access the json array in controller to use it as described.
I have tried a multiple methods of converting given data to an array for the mail method, but with no luck.
Ajax form handling and sending to controller:
$("#save").click(function () {
var notifySelection = $('#notification option:selected').toArray().map(item => item.value);
var Data = {
Place: $('#area').val(),
Part: $('#part').val(),
NokRange: $('#nokRange').val(),
Amount: null,
Warehouse: null,
Failure: $('#failureCode').val(),
ResponsibleQPB: $('#responsibleQPB').val(),
ResponsibleLOG: $('#responsibleLOG').val(),
BlockDate: currDate,
BlockedBy: $('#person').val(),
CusSupp: $('#csName').val(),
Description: $('#description').val(),
EndDate: endDate,
Notifications: JSON.stringify(notifySelection)
}
SaveEvent(Data);
});
function SaveEvent(Data) {
$.ajax({
type: "POST",
url: "../PartBlocking/SaveNewCase",
data: Data,
traditional: true,
success: function (Data) {
if (Data.status) {
window.location.replace("http://somepage/PartBlocking/SuccessfulySaved")
}
},
error: function () {
alert('Uložení se nezdařilo!');
}
});
}
Here is controller:
[HttpPost]
public JsonResult SaveNewCase(PartBlockingModel addNew)
{
var status = false;
var Part = addNew.Part;
var Date = addNew.BlockDate;
var Blockedby = addNew.BlockedBy;
var Place = addNew.Place;
var Description = addNew.Description;
var Notifications = addNew.Notifications;
//This is how i've tried handle the array at last try
//string emails = Notifications;
//string[] email = emails.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
db.PartBlocking.Add(addNew);
int saved = db.SaveChanges();
//notifaction
if (saved > 0)
{
try
{
string body = string.Empty;
using (StreamReader reader = new StreamReader(Server.MapPath("~/EmailTemplates/NewCase.html")))
{
body = reader.ReadToEnd();
}
body = body.Replace("{Part}", Part);
body = body.Replace("{Date}", Date);
body = body.Replace("{BlockedBy}", Blockedby);
body = body.Replace("{Place}", Place);
body = body.Replace("{Description}", Description);
MailMessage mail = new MailMessage();
var sub = "SAPNo | Díl č. - " + Part;
var smtp = new SmtpClient
{
Host = ConfigurationManager.AppSettings["smtp"],
Port = int.Parse(ConfigurationManager.AppSettings["portnumber"]),
EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["IsSsl"]),
DeliveryMethod = SmtpDeliveryMethod.Network
};
mail.From = new MailAddress("postmaster#email.com", "Evidována nová neshoda");
mail.To.Add("xx#email.com");
mail.To.Add("xy#email.com");
//This is how i've tried handle the array at last try
//foreach (var item in Notifications)
//{
// mail.To.Add((item).ToString());
//}
mail.IsBodyHtml = true;
mail.Subject = sub;
mail.Body = body;
smtp.Send(mail);
status = true;
}
catch (Exception ex)
{
ViewBag.Error = ex;
}
}
return new JsonResult { Data = new { status } };
}
}
And model:
public class PartBlockingModel
{
//rest of definition for db
......
......
//definition for notifications
public string Notifications { get; set; }
}
The data are correctly inserted into db and if I use only predifinied emails via mail.To.Add("xy#email.com"), email is sended correctly. What i need is to use Notifications list given by jquery as an email list for MailMessage method.
first of all, make sure you javascript object "Data" is the same structure as C# object "PartBlockingModel"
your ajax request must be as the followinf :
$.ajax({
type: "POST",
url: "../PartBlocking/SaveNewCase",
contentType:"application/json; charset=utf-8"
dataType: 'json',
data: JSON.stringify(Data),
traditional: true,
success: function (Data) {
if (Data.status) {
window.location.replace("http://somepage/PartBlocking/SuccessfulySaved")
}
},
error: function () {
alert('Uložení se nezdařilo!');
}
});
I solved the problem.
In my jquery data binding i've changed
Notifications: JSON.stringify(notifySelection)
to:
Notifications: notifySelection.join(',')
and now in my controller works my solution for listing emails as desired and sendig to email addressess from input.
string[] email = Notifications.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var item in Notifications)
{
mail.To.Add((item).ToString());
}

How to call method using jQuery in mvc razor page at 10 sec interval and append output to html

Below code read messages from iot hub one by one as it comes.
private async void MonitorEventHubAsync(DateTime startTime, CancellationToken ct, string consumerGroupName)
{
EventHubClient eventHubClient = null;
EventHubReceiver eventHubReceiver = null;
try
{
string mesageData = string.Empty;
int eventHubPartitionsCount;
string selectedDevice = "";
eventHubClient = EventHubClient.CreateFromConnectionString("activeIoTHubConnectionString", "messages/events");
mesageData = "Receiving events...\r\n";
eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
string partition = EventHubPartitionKeyResolver.ResolveToPartition(selectedDevice, eventHubPartitionsCount);
eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, startTime);
//receive the events from startTime until current time in a single call and process them
while (true)
{
var eventData = eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(1)).Result;
if (eventData != null)
{
var data = Encoding.UTF8.GetString(eventData.GetBytes());
var enqueuedTime = eventData.EnqueuedTimeUtc.ToLocalTime();
var connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString();
if (string.CompareOrdinal(selectedDevice.ToUpper(), connectionDeviceId.ToUpper()) == 0)
{
mesageData += $"{enqueuedTime}> Device: [{connectionDeviceId}], Data:[{data}]";
if (eventData.Properties.Count > 0)
{
mesageData += "Properties:\r\n";
foreach (var property in eventData.Properties)
{
mesageData += $"'{property.Key}': '{property.Value}'\r\n";
}
}
mesageData += "\r\n";
}
}
}
}
catch (Exception ex)
{
}
}
I want to show messages one by one on mvc cshtml page using above code, how can I do that ?
One approach I can use like below:
In cshtml
<p id="pValue"></p>
In script
var someRootPath = "#Url.Content("~")";
(function randomGenerator() {
$.ajax({
url: someRootPath + 'Home/GetValue',
success: function (data) {
$('#pValue').html(data.someValue);
},
complete: function () {
setTimeout(randomGenerator, 1000);
}
});
})();
Controller
[HttpGet]
public JsonResult GetValue()
{
return Json( // call winform method which gives message data);
}
Something like this
var someRootPath = "#Url.Content("~")";
$(function(){
randomGenerator();
setTimeout(randomGenerator, 1000);
});
function randomGenerator() {
$.ajax({
url: someRootPath + 'Home/GetValue',
success: function (data) {
$('#pValue').html(data.someValue);
}
});
}

How to show message or alert when record insertion success of fail in the controller

In my _Layout.cshtml page there is a textbox that allows user to type his/her email address(this is for newsletter).if typed email address exists it does not insert to the database and if not it insert to the database. at the same time if not inserted I want to show an error message and if insert I want to show success message.this is how I insert to the database,
public ActionResult getNewsLetterMail(string N_id, string N_EmailAdd)
{
Session["Ealert"] = null;
Random random = new Random();
int idONe = random.Next(99, 999);
int idTwo = random.Next(999, 9999);
string middle = "menuka";
string fullID = idONe.ToString() + middle + idTwo.ToString();
var N_ID = fullID;
var N_Email = N_EmailAdd;
TourCenterDBEntities NewsLetterEntities = new TourCenterDBEntities();
var existing = NewsLetterEntities.News_Letter.Where(l => l.N_Email == N_EmailAdd);
Debug.WriteLine(existing.Count());
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
//want to send success text
}
else
{
//want to send error text
}
return Json(new { });
}
if success or error it returns to the same _Layout.csthml page.
how can I do that.hope your help.
You can use. return content.
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
//return Content("Your information saved successfully");
return new JavascriptResult { Script = "alert('Your information saved successfully');" };
}
else
{
//return Content("Already exist. Please choose another.");
return new JavascriptResult { Script = "alert('Your information saved successfully');" };
}
public ActionResult getNewsLetterMail(string N_id, string N_EmailAdd)
{
Session["Ealert"] = null;
Random random = new Random();
int idONe = random.Next(99, 999);
int idTwo = random.Next(999, 9999);
string middle = "menuka";
string fullID = idONe.ToString() + middle + idTwo.ToString();
var N_ID = fullID;
var N_Email = N_EmailAdd;
TourCenterDBEntities NewsLetterEntities = new TourCenterDBEntities();
var existing = NewsLetterEntities.News_Letter.Where(l => l.N_Email == N_EmailAdd);
Debug.WriteLine(existing.Count());
string myMessage="";
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
myMessage="success";
}
else
{
myMessage="failed";
}
return Json(myMessage, JsonRequestBehavior.AllowGet);
}
In your view.
$.post('#Url.Action("getNewsLetterMail", "yourControllerName")', { N_id: N_id, N_EmailAdd: N_EmailAdd }).done(function (data) {
if (data == "success") {
alert("Success!");
}
if( data== "failed") {
alert("Failed!");
}
}
I have no experience but I would try something like that:
in my viewmodel I would put
string info
then in my razor view
#Html.DisplayFor(m=>m.info)
and in controller
if(existing){info="success"}
You would have to pass info to the viewmodel in your controller
public ActionResult getNewsLetterMail(string N_id, string N_EmailAdd)
{
Session["Ealert"] = null;
Random random = new Random();
int idONe = random.Next(99, 999);
int idTwo = random.Next(999, 9999);
string middle = "menuka";
string fullID = idONe.ToString() + middle + idTwo.ToString();
var N_ID = fullID;
var N_Email = N_EmailAdd;
TourCenterDBEntities NewsLetterEntities = new TourCenterDBEntities();
var existing = NewsLetterEntities.News_Letter.Where(l => l.N_Email == N_EmailAdd);
Debug.WriteLine(existing.Count());
string myMessage="";
if (existing.Count() == 0)
{
News_Letter NewsLetterDetails = new News_Letter();
NewsLetterDetails.N_id = N_ID;
NewsLetterDetails.N_Email = N_Email;
NewsLetterEntities.News_Letter.Add(NewsLetterDetails);
NewsLetterEntities.SaveChanges();
myMessage="success!";
}
else
{
myMessage="Failed!";
}
return Json(myMessage, JsonRequestBehavior.AllowGet);
}
In Views, you can add jquery to display the message. Following is an example to retrieve the message in Views. You can edit the names in your form accordingly.
`<script type="text/javascript">
$(document).ready(function () {
$("#yourForm").submit(function (e) {
e.preventDefault();
var valid = $("#yourForm").valid();
if (valid) {
$.ajax({
url: "/getNewsLetterMail",
type: "POST",
data: {
Name: $("#N_id").val(),
Email: $("#N_EmailAdd").val(),
},
success: function (data) {
alert(data);
reset();
}
});
}
});
});
</script>'

404 Error When Accessing URL through AJAX

Not sure why, everything seems formatted fine, but I get the HTTP 404 error when attempting to access a function in my controller. Here's the aspx:
function CheckIfPacked() {
if ($("#OrderNumber").val() != "") {
var url = "/Packing/PackageTracking/CheckIfPacked";
$.ajax({
url: url,
cache: false,
data: "orderNumber=" + $("#OrderNumber").val() + "&actionyes=GetSalesOrder()",
success: function (data) {
var domElement = $(data);
if (data != "") {
$('#MessageDiv').append(domElement);
}
});
}
}
And here's the controller:
public Result CheckIfPacked(string orderNumber) {
var mesEntity = new MESEntities();
var packh = from packhead in mesEntity.Packing_Transaction_Headers
where packhead.Order_No_ == orderNumber
select packhead.Completed_by_Packer;
if (packh.First() == 0)
{
return new Result { Success = true, Message = string.Format("You have not finished packing order {0}, are you sure you want to navigate away from this page?", orderNumber) };
}
else
{
return null;
}
}
I think I've just stared at this too long. Thanks.
your method should be static and you should use webmethod attribute for your function :
[WebMethod]
public static Result CheckIfPacked(string orderNumber) {
var mesEntity = new MESEntities();
var packh = from packhead in mesEntity.Packing_Transaction_Headers
where packhead.Order_No_ == orderNumber
select packhead.Completed_by_Packer;
if (packh.First() == 0)
{
return new Result { Success = true, Message = string.Format("You have not finished packing order {0}, are you sure you want to navigate away from this page?", orderNumber) };
}
else
{
return null;
}
}

When invoked with a jQuery $.ajax, what to return from the Action Method if things go ok?

Here's my code:
[HttpPost]
public ActionResult VoteChampionStrongAgainst(string championStrong, string againstChampion)
{
int champStrongId = int.Parse(championStrong);
int againstChampId = int.Parse(againstChampion);
string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
using (EfCounterPickRepository counterPickRepository = new EfCounterPickRepository())
{
var existingCounterPick = counterPickRepository.FindAll()
.SingleOrDefault(x => x.ChampionStrong == champStrongId && x.AgainstChampion == againstChampId);
//Does this counterpick combination already exist?
if (existingCounterPick != null)
{
//Has this user already voted?
var existingVote = counterPickRepository.FindVoteForUser(ip, existingCounterPick.CounterPickVoteId);
//He hasn't voted, add his vote history.
if (existingVote == null)
{
StrongCounterHistory history = new StrongCounterHistory();
history.IPAddress = ip;
history.VoteType = true;
history.StrongCounterPickVoteId = existingCounterPick.CounterPickVoteId;
counterPickRepository.AddStrongPickHistory(history);
counterPickRepository.SaveChanges();
//Add a total vote the pick.
existingCounterPick.TotalVotes++;
counterPickRepository.SaveChanges();
}
else
{
//Will use this to display an error message.
//How to return an "error" that jquery understands?
}
}
else //This combination doesn't exist. Create it.
{
//Create it....
StrongCounterPickVote newCounterPick = new StrongCounterPickVote();
newCounterPick.ChampionStrong = champStrongId;
newCounterPick.AgainstChampion = againstChampId;
newCounterPick.TotalVotes = 1;
counterPickRepository.CreateNewCounterPick(newCounterPick);
counterPickRepository.SaveChanges();
//Assign a vote history for that user.
StrongCounterHistory history = new StrongCounterHistory();
history.IPAddress = ip;
history.VoteType = true;
history.StrongCounterPickVoteId = newCounterPick.CounterPickVoteId;
counterPickRepository.AddStrongPickHistory(history);
counterPickRepository.SaveChanges();
}
return View();
}
}
Here's my jQuery code:
$(".pick .data .actions .btn-success").click(function () {
var champStrongId = $(this).data("champstrongid");
var againstChampId = $(this).data("againstchampid");
$.ajax({
type: 'POST',
url: "/Counterpicks/VoteChampionStrongAgainst",
data: { championStrong: champStrongId, againstChampion: againstChampId },
success: function () {
alert("Great success!");
},
error: function (e) {
alert("Something bad happened!");
console.log(e);
}
});
});
What do I need to return from my ActionMethod so the code execution enters success: if things went OK, or error: if things go wrong (for example, he already voted on this particular counter pick?
Servlet should answer a "200 OK" HTTP response.
Don't know about your 'View' api, but HttpServletResponse.setStatus(200) would do on the Java side. Don't forget, you can request the AJAX url manually in your browser to see what it is returning..
Here's some things I'd do...
public JsonResult VoteChampionStrongAgainst(string championStrong, string againstChampion) {
var success = true;
// Do all of your data stuff
return Json(new { success = success, error = 'Some error message'});
}
The JsonResult is a special ActionResult for returning Json. It automatically sets the correct headers for the browser. The Json() will use ASP.NET's built in serializer to serialize an anonymous object to return to the client.
Then with your jQuery code...
$.ajax({
type: 'POST',
url: "/Counterpicks/VoteChampionStrongAgainst",
data: { championStrong: champStrongId, againstChampion: againstChampId },
success: function (json) {
if (json.success) {
alert("Great success!");
}
else if(json.error && json.error.length) {
alert(json.error);
}
},
// This error is only for responses with codes other than a
// 200 back from the server.
error: function (e) {
alert("Something bad happened!");
console.log(e);
}
});
In order to have the error fire you'd have to return a different response code with Response.StatusCode = (int)HttpStatusCode.BadRequest;
You can return 500 internal server error if there are any errors on your server something like
Response.StatusCode = (int)HttpStatusCode.InternalServerError;
Response.ContentType = "text/plain";
return Json(new { "internal error message"});

Categories