Link to home
Create AccountLog in
Avatar of Isaac Johnson
Isaac JohnsonFlag for United States of America

asked on

Embed Javascript in webAPI Controller

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

Avatar of kaufmed
kaufmed
Flag of United States of America image

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?
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 -User generated image-saige-
Avatar of Isaac Johnson

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of Kelvin McDaniel
Kelvin McDaniel
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer