Redirect from javascript in asp razer view - javascript

I have following Jquery code the code is sending data to controller fine and now I want to redirect from here after success how can I achieve this
$('#reply_admin').click(function () {
var recipName = $('.input_eply').val();
var id =#Model.id
$.post('/Admincontact/Replt/' + id,
{ reply: recipName },
function (data) {
$('#reply').append(data);
window.location.href = '#Url.Action("Index", "Admincontact")';
});
});
and my controller is
[HttpPost]
public ActionResult Replt(string reply,string id)
{
EmailManager.admin_reply(db.contactUs.Find(Convert.ToInt32(id)).Email, reply);
return new EmptyResult();
}

Whats the meaning of
$('#reply').append(data);
If you are returning EmptyResult()
Try only
function (data) {
window.location.href = '#Url.Action("Index", "Admincontact")';
}

Related

Calling window.onload inside a cshtml view

I am trying to call a window.onload function inside a cshtml view.
My code looks like this.
#model BusinessModel
#if(Model.Business != null)
{
<script>
window.onload = function () {
if ('#Model.Business'!='') {
var data = {
//JSON Object
};
$.ajax({
url: www.google.com,
method: 'POST',
headers:{},
data : JSON.stringify(data),
success: function (response){
window.location.replace(new url);
}
});
return false;
}
}
</script>
} else {
// Some basic HTML code
}
When i am trying to do something like this, when the condition matches it is never hitting the window.onload function.
Am i doing something wrong or Does this need to be handled in a different way?
Please help me with this
Thanks.
You can try to check if Model.Business is null in js.Here is a demo:
Model:
public class BusinessModel
{
public List<Business> Business { get; set; }
}
Action:
public IActionResult Test1()
{
var model = new BusinessModel { Business = new List<Business>() };
return View(model);
}
View:
#model BusinessModel
#if (Model.Business == null)
{
<h1>null</h1>
// Some basic HTML code
}
<script>
window.onload = function () {
if ('#Model.Business'!='') {
alert("Hello");
}
}
</script>
result:

public action method was not found on the controller

I'm getting an error that my Action Method was not found, but can't figure out what's wrong. I searched the internet now for hours but haven't found a solution till now.
In my View I have a JavaScript function:
<script type="text/javascript">
function ShowHideAds(button) {
var dAds = document.getElementById("dAds");
if (dAds.style.display == "none") {
dAds.style.display = "block"
var txtBox = "Visible";
$.post('#Html.Action("GetState","Rights")', { txtAds: txtBox });
}
else {
dAds.style.display = "none"
var txtBox = "Hidden";
$.post('#Html.Action("GetState", "Rights")', { txtAds: txtBox });
}
} </script>
I'm switching between a Textbox and a Listbox and depending on which is visible, I want to pass the parameter to my method.
My method in my Controller is the following:
[HttpPost, ActionName("GetState")]
public ActionResult GetState(string txtAds, string txtRg)
{
if (txtAds != null)
stateTxtAds = txtAds;
if (txtRg != null)
stateTxtRg = txtRg;
return View();
}
and finally here is my routing:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Before using the #Html.Action() method I had following line of code:
$.post("/Rights/GetState", { txtAds: txtBox });
but this did not work when the project was deployed so I tried to use the #Html.Action two send my variables to my controller method.
Can anyone help please?
Thank you!
GetState(string txtAds, string txtRg) has two parameters but you are only providing one. If you want it to accept two but only provide it one like you are doing in the call, do the following.
For example for the post #Html.Action("GetState", "Rights")', { txtAds: txtBox }:
GetState(string txtAds, string txtRg = "")
This way you can just send txtAds if you want and it should reach it.
The ajax I would recommend:
var json = '{txtAds: "' + txtAds + '"}'
$.ajax({
url:'#Url.Action("GetState", "Rights")',
type:'POST',
data: json,
contentType: 'Application/json',
success: function(result){
// Whatever you want to do next.
}
})

How to Send an Email from client side JS using my backend

I have class method for sending Email
public static bool SendEmail(string msg)
{
var sent = false;
try
{
var fromEmail = ConfigurationManager.AppSettings["FromEmail"];
var toEmail = ConfigurationManager.AppSettings["ToEmail"];
var emailsubject=ConfigurationManager.AppSettings["ErrorTitle"];
var emailService = new EmailServiceClient();
sent = emailService.SendEmail(fromEmail, toEmail, emailsubject, msg);
}
catch (Exception ex)
{
LogException(ex);
}
return sent;
}
Here is my Javascript function on on button Click() event
function sendMail() {
var e= "Hi";
$.ajax({
url: '/Home/SendEmail',
method: "POST",
success:function (result) {
alert('Email Sent');
},
error: function (result) {
alert('Email Does Not Sent');
}
});
}
This JS code is opening an outlook email of my system (open my mail client).
I want to send the email on button click from my webpage directly via EmailService (not by SMTP because I have WCF created for EmailService), I am not understanding flow that how can I achieve it.
Need to know changes in JS code and Any documentation or example for reference would be helpful.
Thank You
It worked with this:
public ActionResult SendEmail(string msg)
{
var sent = false;
try
{
var emailClient = new EmailServiceReference.EmailServiceClient();
sent = emailClient.SendEmail(fromEmail, toEmail, emailsubject, msg); /// All parameters of SendEmail method defined
}
catch (Exception ex)
{
Console.WriteLine("Exception occured while sending Email " + ex.Message);
}
return Json(sent, JsonRequestBehavior.AllowGet);
}
I recommend you to read about jquery and how to use the jquery ajax , the code below is a good point to start, you did not mention if you are using MVC or API or WebForms, so code below is a bit generic. (this is a complete guide that you can follow)
function SendMail(){
var msg = 'your msg';
$.ajax({
url: 'YOURURLHERE/SendEmail?msg=' + msg,
method: "GET",
}).done(function (result) {
alert('Email Sent');
});
});
}

Ajax request not posting ID to controller

I have wrote an AJAX post request to my deletewidget controller, it is posting the request token fine, however it does not seem to pass the widgetID to the controller. I have stepped through the javascript code and it assigns the ID to the variable widgetID fine, and have also put a breakpoint in my controller but it says null.
$(document).ready(function () {
$('#columns').on('click', '.glyphicon.glyphicon-trash', function (event) {
var panel = this;
//get id here
//toggle the modal
$('#deleteWidgetModal').modal('show');
var widgetID = $(this).closest('.panel.panel-default').attr('data-widgetid');
document.getElementById('delete-widget').onclick = function (event) {
event.stopPropagation();
//anti forgery token
//get the form
var form = $('#__AjaxAntiForgeryForm');
//from the form get the antiforgerytoken
var token = $('input[name="__RequestVerificationToken"]', form).val();
var URL = '/Dashboard/DeleteWidgetConfirmed';
//we make an ajax call to the controller on click
//because the controller has a AntiForgeryToken attribute
//we need to get the token from the form and pass it with the ajax call.
$.ajax({
url: URL,
data: {
__RequestVerificationToken: token,
id: widgetID
},
type: 'POST',
success: function(result){
var parentElement = $(panel).closest(".col-md-4.column");
var targetElement = $(panel).closest(".panel.panel-default");
targetElement.remove();
//parentElement.addClass("expand-panel");
checkEmptyPanelContainers();
$('#deleteWidgetModal').modal('hide');
},
error: function (jqXHR, textStatus, errorThrown) {
alert("An error has occurred please contact admin");
}
})
}
return false;
})
});
and here is my controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteWidgetConfirmed(int? id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
WidgetModel widgetModel = db.widgets.Find(id);
db.widgets.Remove(widgetModel);
db.SaveChanges();
return new EmptyResult();
}
It seemed to be executing the ajax code twice, I moved my return false up one level and it solved the problem

How to get rid of Serialization in MVC

I have created a jQuery code which will take a form(which is in my view) and it will serialize it and it will post that to my controller.......Jquery code looks like this......
$(document).ready(function () {
$('#submit').click(function () {
var jsonObj = $('#form').serialize();
$.ajax({
type: "POST",
url: "../Home/Index",
data: JSON.stringify({ "cus": jsonObj }),
success: function(data){
alert(data + "done");
},
error:function(){
alert("Error!!!!");
}
});
});
});
This is how my controller method looks like:..........
[HttpPost]
public ActionResult Index(Customer cus)
{
string str = null;
if (cus.Name == "jude")
str = "Success";
else
str = "Error!!";
return Json(str);
}
Now i need to undo the serialization inside my controller method......can someone please give me an idea to do this..........
I have tried two ways to do this but didn't work.....
1 - var model = (Customer)cus.Deserialize();
2 - JavaScriptSerializer js = new JavaScriptSerializer();
var cus1 = js.Deserialize<Customer>(cus);

Categories

Resources