We help IT Professionals succeed at work.

Embed Javascript in webAPI Controller

TechIsaac
TechIsaac asked
on
67 Views
Last Modified: 2019-02-15
I  am using a webapi controller in which I want to use javascript to convert the
current date to mmddyy before passing as a string to the model.

Can I use javascript in the controller and how would I do this?

//controller
using picture_of_the_day.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace picture_of_the_day.Controllers
{
    public class PicOfTheDayController : ApiController
    {
        [Route("api/PicOfTheday/GetPicByDate/{date}")]
        [HttpGet]
        public IHttpActionResult GetPicByDate(string date)
        {
            try
            {
                var pic = new Picture(date);

                return Ok(pic);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
    }
}
//Model
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace picture_of_the_day.Models
{
    public class Picture
    {
        public int SequenceNum { get; set; }
        public string Date { get; set; }
        public string Caption { get; set; }
        public bool Active { get; set; }
        public DateTime DisplayDate { get; set; }
        public string FileName { get; set; }

        public Picture(string picDate)
        {
            using (var sqlConn = Database.GetConnection())
            {
                using (SqlCommand command = new SqlCommand("insight_sel_pic_day", sqlConn))
                {
                    command.CommandType = System.Data.CommandType.StoredProcedure;

                    //add parameters
                    command.Parameters.Add("@INpic_date", SqlDbType.VarChar).Value = picDate;

                    // execute stored procedure
                    sqlConn.Open();
                    using (SqlDataReader rdr = command.ExecuteReader())
                    {
                        // check for rows
                        if (rdr.HasRows)
                        {
                            rdr.Read();
                            
                            Active = true;
                            Caption = rdr["caption"].ToString().Trim();
                            Date = picDate;
                            FileName = picDate;
                        }
                    }
                }
            }
        }
    }
}

Open in new window

Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015

Commented:
Can I use javascript in the controller and how would I do this?
No.

I want to...convert the date to mmddyy before passing as a string to the model.
Sounds reasonable, but not entirely clear. Are we talking about submitting data from the client to the server, or are we talking about returning data from the server to the client?
it_saigeDeveloper
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
If you are getting a Date string, you could validate it as a date in the controller and then send the formatted string to the repository (don't forget to separate your concerns); e.g. -

Picture.cs -
using System;

namespace EE_Q29135748.Models
{
    public class Picture
    {
        public int SequenceNum { get; set; }
        public string Date { get; set; }
        public string Caption { get; set; }
        public bool Active { get; set; }
        public DateTime DisplayDate { get; set; }
        public string FileName { get; set; }
    }
}

Open in new window

PicOfTheDayRepository.cs -
using EE_Q29135748.Models;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace EE_Q29135748.Repositories
{
    public class PicOfTheDayRepository
    {
        public Picture GetPicOfTheDay(string date)
        {
            // Here is where you would get the data, for now we will just mock it
            var pictures = Enumerable.Range(0, 10).Select(x => new Picture { Active = true, Caption = $"Picture_{x}_Caption", Date = DateTime.Now.AddDays(x).ToString("MMddyy"), FileName = DateTime.Now.AddDays(x).ToString("MMddyy") });
            return pictures.FirstOrDefault(p => p.Date.Equals(date));
            //Picture picture = default(Picture);
            //using (var connection = Database.GetConnection())
            //{
            //    using (var command = new SqlCommand("insight_sel_pic_day", connection))
            //    {
            //        command.CommandType = System.Data.CommandType.StoredProcedure;

            //        //add parameters
            //        command.Parameters.Add("@INpic_date", SqlDbType.VarChar).Value = date;

            //        // execute stored procedure
            //        connection.Open();
            //        using (var rdr = command.ExecuteReader())
            //        {
            //            // check for rows
            //            if (rdr.HasRows)
            //            {
            //                rdr.Read();
            //                picture = new Picture
            //                {
            //                    Active = true,
            //                    Caption = rdr["caption"]?.ToString().Trim() ?? "",
            //                    Date = date,
            //                    FileName = date
            //                };
            //            }
            //        }
            //    }
            //}
            //return picture;
        }
    }
}

Open in new window

PicOfTheDayController.cs -
using EE_Q29135748.Repositories;
using System;
using System.Web.Http;

namespace EE_Q29135748.Controllers
{
    public class PicOfTheDayController : ApiController
    {
        [Route("api/PicOfTheDay/GetPicByDate/{date}")]
        [HttpGet]
        public IHttpActionResult GetPicByDate(string date)
        {
            try
            {
                DateTime converted = default(DateTime);
                PicOfTheDayRepository repository = new PicOfTheDayRepository();
                if (DateTime.TryParse(date, out converted))
                {
                    var picture = repository.GetPicOfTheDay(converted.ToString("MMddyy"));

                    return Ok(picture);
                }
                return NotFound();
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
    }
}

Open in new window

Which produces the following output -Capture.PNG-saige-
TechIsaacIT Contracting

Author

Commented:
What I have just been request to do is to create a angular module to
consume to current date, reformat the date to mmddyy to be used to
query the database with the reformatted date.

I'm talking angular.module with what I think maybe filter('formatDate' with the current date as
input returning formatted date.  Not sure of the structure being new to angular.module
Sr. Developer
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.