mvc email with controller action as attachment - asp.net-mvc

is it possible to pass a controller action as path on smtp email?
I have this method in my controller which gets me what i searched for:
public void ConnectToDatabase(Modelclass uc)
{
// IList<Modelclass> list = new List<Modelclass>();
var query = (from a in db.DBTable
where a.IDNumber.Equals(uc.ID_Number)
select a).ToList();
var tt = query;
}
and i call this method on this action on the same controller:
[HttpPost]
public ActionResult GetUserInput(ModelClass model )
{
var idnumber = model.ID_Number;
var startdate = model.Start_Date;
var enddate = model.End_Date;
ConnectToDatabase(model);
// validate your date here and return True if validated
if (model.End_Date < model.Start_Date)
{
return Json(false);
}
return View("Search");
}
so i want to pass this "connectToDatabase" method as an attachment to the email il be sending.
where do i even start?

Not sure if this is what you wanted but you can write a Url.Action to your stmp email like this.
var callbackUrl = Url.Action("Action", "Controller",
new
{
Idnumber = model.ID_Number;
Startdate = model.Start_Date;
Enddate = model.End_Date;
}, protocol: Request.Url.Scheme);
Then assign the url into your email
message.Body =String.Format("<b><i>Click the following link to view attachment</i></b> here");
After that write your controller with the same matching parameters with Url.Action
public void ConnectToDatabase(string IdNumber, DateTime Startdate, DateTime Enddate)
{
//do something here...
}

Related

How to pass user input from view to a class in MVC

I imagine this must be pretty basic, but all my search results only show how to pass data the other way ( model to controller, controller to view, and then view back to controller, but nothing from controller back to model(class). I am trying to pass user input for a search parameter into the query string for an API. In the view:
<form method="post" action="~/Models/Search">
<input name="artist" placeholder="Enter artist's name" />
#{Search temp = new Search();
if (Request.Form["artist"] != null) //this method doesn't work; trying to get user response and pass it back to search class;
{ temp.Artist = Request.Form["artist"].ToLower(); } //have to hardcode search parameter at this time
}
<!--<button>Click Me</button>-->
<script>
var weather = Object();
$(document).ready(function () {
$('button').click(function () {
// var artist = $("#artist").val();
$.get("#Url.Action("SearchArtist", "Home")", function (response) {
console.log(response);
artistInfo = ko.mapping.fromJS(response); //populate the artist search object
ko.applyBindings(artistInfo);
});
});
});
The class:
public class Search
{
string artist;
public string Artist { get; set;}
public Object getArtistInfo()
{
string appID = "*************** ";
artist = "metallica";
string url = "http://developer.echonest.com/api/v4/artist/search?api_key="+ appID + "&format=json&name=" + artist + "&results=1&bucket=genre&bucket=songs";
//synchronous client;
var client = new WebClient();
var content = client.DownloadString(url);
var serializer = new JavaScriptSerializer();
var jsonContent = serializer.Deserialize<Object>(content);
return jsonContent;
}
}
The controller:
public ActionResult ArtistInfo()
{
return View();
}
public JsonResult SearchArtist()
{
Search artist = new Search();
return Json(artist.getArtistInfo(), JsonRequestBehavior.AllowGet);
}
Try to add attributes (runat="server" and id="chooseyourid") to html forms results below :
if you want to access to values in your code behinde you just need to write the id of your element like below :
/artiste.value;/

Date Format Switched Passing Parameter From Jquery to Controller

I am using the following in my view:
var myDate = $(inpDateCompleted).val();
alert(myDate)
var url = '#(Url.Action("HoursByDay", "DashBoard"))?dateCompleted=' + myDate;
alert(url)
Both alerts correctly display the date format as 01/11/2011 (1st of November). However once the date is passed into in my controller event via the above url the date is incorrect as 11/01/2011(11th of January):
[HttpGet]
public ActionResult HoursByDay(DateTime dateCompleted)
{
var s = ExecuteSqlCommand2(dateCompleted);
return Content(s, "application/json");
}
And the data produced is incorrect. How can I correct this?
As per recommendations I have set the culture using:
var localizationOptions = new RequestLocalizationOptions
{
// Set options here to change middleware behavior
SupportedCultures = new List<CultureInfo>
{
new CultureInfo("en-NZ"),
},
SupportedUICultures = new List<CultureInfo>
{
new CultureInfo("en-NZ"),
}
};
app.UseRequestLocalization(localizationOptions, defaultRequestCulture: new RequestCulture("en-NZ"));
If you know your date string will be always in the dd/MM/yyyy format, you may use the DateTime.TryParseExact method to build a datetime object from a string. Change your Action method parameter to a string and parse this string with the pattern/format.
[HttpGet]
public ActionResult HoursByDay(string dateCompleted)
{
DateTime parsedDate;
if(DateTime.TryParseExact(dateCompleted,"dd/MM/yyyy",CultureInfo.CurrentCulture,
DateTimeStyles.None,out parsedDate))
{
// parsedDate is a valid DateTime object now
var s = ExecuteSqlCommand2(parsedDate);
return Json(s);
}
else
{
// could not create a valid DateTime object from inputString
// to do :return something
}
}

Redirecting from ane action to another controller action in mvc

This is my code where I want to post some data(date of calendar here) to "index" action of "home" controller and want to save this data in the database and at the same time I want to redirect to another action of another controller i.e "Index" action of "Home" controller
here is my jquery code below,
function getDate() {
$('.cal_daybox').on('click', function () {
var timestamp = parseInt($(this).attr('id'));
var day = new Date(timestamp);
alert("You clicked " + day.toDateString());
var url = '#Url.Content("~/Home/Index")';
var date = day.toDateString();
$.ajax({
type: "POST",
url: url,
data: { date: day.toDateString() },
dataType:"json"
});
return false;
});
EventsController.cs
public ActionResult Index()
{
return View(db.Events.ToList());
}
HomeController.cs
[HttpPost]
public ActionResult Index(DateTime date)
{
Date dt = new Date();
dt.StartDate = date;
db.Dates.Add(dt);
db.SaveChanges();
return RedirectToAction("Index", "Events", new { id = dt.DateID });
}
Your Index Action of Events Controller does not have a parameter to recieve the Dateid value.It is unable to Find a Action that could recieve a DateId val.
You need to either modify your existing Action or add an Action Overload like this
public ActionResult Index(DateTime dateId)
{
//Do something with the val
}
public ActionResult Index()
{
return View(db.Events.ToList());
}
you are calling controller action using ajax so in this case you have to change you action method and jquery call like this:
[HttpPost]
public ActionResult Index(DateTime date)
{
Date dt = new Date();
dt.StartDate = date;
db.Dates.Add(dt);
db.SaveChanges();
return Json(dt.DateID,JsonAllowBehaviour.AllowGet);
// return RedirectToAction("Index", "Events", new { id = dt.DateID });
}
function getDate() {
$('.cal_daybox').on('click', function () {
var timestamp = parseInt($(this).attr('id'));
var day = new Date(timestamp);
alert("You clicked " + day.toDateString());
var url = '#Url.Content("~/Home/Index")';
var date = day.toDateString();
$.ajax({
type: "POST",
url: url,
data: { date: day.toDateString() },
dataType:"json",
onsuccess:function(id)
{
window.location='/Events/Index?Id='+id;
}
});
return false;
});
And also please change your index action of Events Controller like below:
public ActionResult Index(int Id=0)
{
return View(db.Events.ToList());
}

How do i have optional parameter but still validate them in asp.net mvc routing?

I have this route that i just added
routes.MapRoute(
"MyRoute",
"MyController/{action}/{orgId}/{startDate}/{endDate}",
new
{
controller = "MyController",
action = "MyAction",
orgId = 0,
startDate = DateTime.Today.AddMonths(-1),
endDate = DateTime.Today
},
new
{
action = new FromValuesListConstraint(new string[] { "MyAction", "MyActionEx" }),
orgId = new IntegerRouteConstraint(),
startDate = new DateTimeRouteConstraint(),
endDate = new DateTimeRouteConstraint()
}
when i put in this url, it resolves down to the default route (controller, action,id) and the above rout does not catch this url:
http://localhost:1713/MyController/MyAction/16
But this below works fine.
http://localhost:1713/MyController/MyAction/16/11-May-10/11-May-10
my question is that i thought both would work as i am giving default values to the startDate and enddate fields
i tested this using the RouteDebugger and this route turned up false
how can i have these last two parameter as optional but still have the validation ?
The problem is this in this current format does not fit to your route (requires 5-part URL).
You may change this line
startDate = DateTime.Today.AddMonths(-1),
endDate = DateTime.Today
to
startDate = UrlParameter.Optional,
endDate = UrlParameter.Optional
And do the conversion and defaults in the controller itself.
You could follow #Aliostad's method and then write your own action filter attribute to validate the parameters that are coming into the method. If they don't validate against your constraints then reject the url as you would normally.
public class ValidateParameterFilter : ActionFilterAttribute
{
base.OnActionExecuting(filterContext);
bool areParametersValid = true;
if (filterContext.ActionParameters.ContainsKey("startDate"))
{
DateTime startDate;
if (!DateTime.TryParse(filterContext.ActionParameters["startDate"].ToString(), out startDate))
{
// Not a DateTime so bad data in here
areParametersValid = false;
}
}
if (filterContext.ActionParameters.ContainsKey("endDate"))
{
DateTime endDate;
if (!DateTime.TryParse(filterContext.ActionParameters["endDate"].ToString(), out endDate))
{
// Not a DateTime so bad data in here
areParametersValid = false;
}
}
if (!areParametersValid)
{
// Redirect to error page or throw an exception
}
}
Then on your action just decorate it with the attribute
[ValidateParameterFilter]
public ActionResult MyAction (int orgId, DateTime startDate, DateTime endDate)
{
...
}
Although I thought if you had the type declared as DateTime then an abc value would get rejected.

ASP.NET MVC: Server Validation & Keeping URL paramters when returning the view

I currently have the following code for the POST to edit a customer note.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditNote(Note note)
{
if (ValidateNote(note))
{
_customerRepository.Save(note);
return RedirectToAction("Notes", "Customers", new { id = note.CustomerID.ToString() });
}
else
{
var _customer = _customerRepository.GetCustomer(new Customer() { CustomerID = Convert.ToInt32(note.CustomerID) });
var _notePriorities = _customerRepository.GetNotePriorities(new Paging(), new NotePriority() { NotePriorityActive = true });
IEnumerable<SelectListItem> _selectNotePriorities = from c in _notePriorities
select new SelectListItem
{
Text = c.NotePriorityName,
Value = c.NotePriorityID.ToString()
};
var viewState = new GenericViewState
{
Customer = _customer,
SelectNotePriorities = _selectNotePriorities
};
return View(viewState);
}
}
If Validation fails, I want it to render the EditNote view again but preserve the url parameters (NoteID and CustomerID) for something like this: "http://localhost:63137/Customers/EditNote/?NoteID=7&CustomerID=28"
Any ideas on how to accomplish this?
Thanks!
This action is hit by using a post. Wouldn't you want the params to come through as part of the form rather than in the url?
If you do want it, I suppose you could do a RedirectToAction to the edit GET action which contains the noteId and customerId. This would effectively make your action look like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditNote(Note note)
{
if (ValidateNote(note))
{
_customerRepository.Save(note);
return RedirectToAction("Notes", "Customers", new { id = note.CustomerID.ToString() });
}
//It's failed, so do a redirect to action. The EditNote action here would point to the original edit note url.
return RedirectToAction("EditNote", "Customers", new { id = note.CustomerID.ToString() });
}
The benefit of this is that you've removed the need to duplicate your code that gets the customer, notes and wotnot. The downside (although I can't see where it does it here) is that you're not returning validation failures.

Resources