locked
Is there a way to pass back a url using ajax/json RRS feed

  • Question

  • User2130491911 posted

    So I have a url stored in a database and I need to render that URL on the  an MVC razor view along with other information.

    Currently I am able to get the data back from the mvc crontroller using the follow

    The Ajax/json stuff

            function ValidateContestant(Contestant_ID)
            {
                //Get Contestant/Candidate Bio-Info to display on screen storing the ID To the Record
    
    
                //Contestant_ID = Contestant_ID || 0;
    
                var data = { Contestant_ID: $('#JWS_CANDIDATE_ID').val() };
    
                $.ajax
                    (
                        {
                            url: '@Url.Action("ValidateContestant","JWS")',
                            type: 'POST',
                            DataType: 'Json',
                            contentType: 'application/json; charset=utf-8',
                            traditional: true,
                            data: JSON.stringify(data),
                            success: function (data)
                            {
                                $('#CANDIDATE_DETAILS').html(""); //Clear Old Value
                                $('#CANDIDATE_DETAILS').val(data); //Clear Old Value
                                $('#lblCandidate').show();
                                $('#CANDIDATE_DETAILS').show();
                            }
    
                        }
    
                    )
    
            }

    The Mvc Controller actionresult that gets called

      [HttpPost]
                                
            public ActionResult ValidateContestant (int Contestant_ID)
            {
                string ContestantData = "";
    
                var Results = db.CM_CONTESTANTS_MASTER_DETAIL_TBL.FirstOrDefault(c => c.MC_CONTESTANT_ID == Contestant_ID);
    
                var sb = new StringBuilder();
    
                sb.Append(Results.MC_CONTESTANT_FIRST_NAME.ToString() + " " + Results.MC_CONTESTANT_LAST_NAME.ToString());
                sb.AppendLine();
                sb.Append(Results.MC_CONTESTANT_DOB.ToString());
                sb.AppendLine();
                sb.Append(Results.MC_CONTESTANT_VIDEO_FILE.ToString());
                       
                ContestantData = sb.ToString();
              
                return Json(ContestantData);
    
            }

    Or is there a way to call a second function  from the ajax function? In the second function I can get the URL and pass it back to the view by itself but its is all triggered by data input in one field on the MVC view

            [HttpPost]
            public ActionResult GetContestantVideoLink(int Contestant_ID)
            {
    
                //GET video link and turn it to url in view
                //see:https://stackoverflow.com/questions/16921481/how-do-i-pass-a-link-through-viewdata-in-mvc-4
    
                var Results = db.CM_CONTESTANTS_MASTER_DETAIL_TBL.FirstOrDefault(c => c.MC_CONTESTANT_ID == Contestant_ID);
    
                string VideoLink = Results.MC_CONTESTANT_VIDEO_FILE.ToString();
    
                ViewData["CVideoLink"] = VideoLink;
    
                return View();
    
            }

    The goal is to have it so the URL stored in the database is clickable from the mvc view.

    Monday, September 14, 2020 9:43 PM

Answers

  • User475983607 posted

    I think the problem has to do with not understanding basic HTML.  I took the liberty of cleaning up the code and redesigning the HTML as a template for holding structured data.  Rather than trying to display a string response, data is returned from the action.  Then we just take the data and stick it in the template HTML.  The design allows you can change the UI (the HTML) without having to mess with the C# code; actions and LINQ.

    Below is the View with the AJAX and template HTML.  I changed the AJAX to a GET and added the ID as a route parameter.  IMHO this is a more appropriate approach because the code is getting data not updating data.  Use POST when inserting or updating data.  

    @{
        ViewBag.Title = "Index";
    }
    
    <h1>Index</h1>
    
    <div>
        <input id="JWS_CANDIDATE_ID" name="JWS_CANDIDATE_ID" type="text" value="1" />
        <input id="GetCandidate" type="button" value="Get Candidate" />
    </div>
    
    
    <div id="CANDIDATE_DETAILS" style="display:none;">
        <div>
            <span id="MC_CONTESTANT_FIRST_NAME"></span>
            <span id="MC_CONTESTANT_LAST_NAME"></span>
        </div>
        <div id="MC_CONTESTANT_DOB"></div>
        <div>
            <a id="MC_CONTESTANT_VIDEO_FILE" href=""></a>
        </div>
    </div>
    
    
    @section scripts{
        <script>
            $('#GetCandidate').click(function (e) {
                ValidateContestant();
            });
    
            function ValidateContestant() {
                $.ajax({
                    url: '@Url.Action("ValidateContestant", "Ajax")/' + $('#JWS_CANDIDATE_ID').val(),
                    type: 'get',
                    dataType: 'Json',
                    success: function (data) {
                        console.log(data);
    
                        //Populate the HTML
                        $('#MC_CONTESTANT_FIRST_NAME').text(data.Firstname);
                        $('#MC_CONTESTANT_LAST_NAME').text(data.Lastname);
                        $('#MC_CONTESTANT_DOB').text(data.BirthDate);
                        $('#MC_CONTESTANT_VIDEO_FILE').text(data.VideoPath);
    
                        $('#lblCandidate').show();
                        $('#CANDIDATE_DETAILS').show();
                    }
                });
            }
        </script>
    }

    Next are the actions.  Notice the code is taking the LINQ results and placing values in a data structure (ContestantDetail).  The data structure is returned from the action and the AJAX Success handler.  also notice the structure matches the HTML template.

    // GET: Ajax
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
    
    [HttpGet]
    public ActionResult ValidateContestant(int id)
    {
        CM_CONTESTANTS_MASTER_DETAIL_TBL Results = db.CM_CONTESTANTS_MASTER_DETAIL_TBL.FirstOrDefault(c => c.MC_CONTESTANT_ID == id);
    
        ContestantDetail data = new ContestantDetail()
        {
            ContestantId = Results.MC_CONTESTANT_ID,
            Firstname = Results.MC_CONTESTANT_FIRST_NAME,
            Lastname = Results.MC_CONTESTANT_LAST_NAME,
            BirthDate = Results.MC_CONTESTANT_DOB.ToShortDateString(),
            VideoPath = Results.MC_CONTESTANT_VIDEO_FILE
        };
    
        return Json(data, JsonRequestBehavior.AllowGet);
    }

    The data structure has the following shape which again matches the HTML template.

        public class ContestantDetail
        {
            public int ContestantId { get; set; }
            public string Firstname { get; set; }
            public string Lastname { get; set; }
            public string BirthDate { get; set; }
            public string VideoPath { get; set; }
        }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 14, 2020 11:52 PM

All replies

  • User475983607 posted

    I think the problem has to do with not understanding basic HTML.  I took the liberty of cleaning up the code and redesigning the HTML as a template for holding structured data.  Rather than trying to display a string response, data is returned from the action.  Then we just take the data and stick it in the template HTML.  The design allows you can change the UI (the HTML) without having to mess with the C# code; actions and LINQ.

    Below is the View with the AJAX and template HTML.  I changed the AJAX to a GET and added the ID as a route parameter.  IMHO this is a more appropriate approach because the code is getting data not updating data.  Use POST when inserting or updating data.  

    @{
        ViewBag.Title = "Index";
    }
    
    <h1>Index</h1>
    
    <div>
        <input id="JWS_CANDIDATE_ID" name="JWS_CANDIDATE_ID" type="text" value="1" />
        <input id="GetCandidate" type="button" value="Get Candidate" />
    </div>
    
    
    <div id="CANDIDATE_DETAILS" style="display:none;">
        <div>
            <span id="MC_CONTESTANT_FIRST_NAME"></span>
            <span id="MC_CONTESTANT_LAST_NAME"></span>
        </div>
        <div id="MC_CONTESTANT_DOB"></div>
        <div>
            <a id="MC_CONTESTANT_VIDEO_FILE" href=""></a>
        </div>
    </div>
    
    
    @section scripts{
        <script>
            $('#GetCandidate').click(function (e) {
                ValidateContestant();
            });
    
            function ValidateContestant() {
                $.ajax({
                    url: '@Url.Action("ValidateContestant", "Ajax")/' + $('#JWS_CANDIDATE_ID').val(),
                    type: 'get',
                    dataType: 'Json',
                    success: function (data) {
                        console.log(data);
    
                        //Populate the HTML
                        $('#MC_CONTESTANT_FIRST_NAME').text(data.Firstname);
                        $('#MC_CONTESTANT_LAST_NAME').text(data.Lastname);
                        $('#MC_CONTESTANT_DOB').text(data.BirthDate);
                        $('#MC_CONTESTANT_VIDEO_FILE').text(data.VideoPath);
    
                        $('#lblCandidate').show();
                        $('#CANDIDATE_DETAILS').show();
                    }
                });
            }
        </script>
    }

    Next are the actions.  Notice the code is taking the LINQ results and placing values in a data structure (ContestantDetail).  The data structure is returned from the action and the AJAX Success handler.  also notice the structure matches the HTML template.

    // GET: Ajax
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }
    
    [HttpGet]
    public ActionResult ValidateContestant(int id)
    {
        CM_CONTESTANTS_MASTER_DETAIL_TBL Results = db.CM_CONTESTANTS_MASTER_DETAIL_TBL.FirstOrDefault(c => c.MC_CONTESTANT_ID == id);
    
        ContestantDetail data = new ContestantDetail()
        {
            ContestantId = Results.MC_CONTESTANT_ID,
            Firstname = Results.MC_CONTESTANT_FIRST_NAME,
            Lastname = Results.MC_CONTESTANT_LAST_NAME,
            BirthDate = Results.MC_CONTESTANT_DOB.ToShortDateString(),
            VideoPath = Results.MC_CONTESTANT_VIDEO_FILE
        };
    
        return Json(data, JsonRequestBehavior.AllowGet);
    }

    The data structure has the following shape which again matches the HTML template.

        public class ContestantDetail
        {
            public int ContestantId { get; set; }
            public string Firstname { get; set; }
            public string Lastname { get; set; }
            public string BirthDate { get; set; }
            public string VideoPath { get; set; }
        }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, September 14, 2020 11:52 PM
  • User2130491911 posted

    Wow I did not what you to write the program. I feel bad now.  I guess; based on this amazing reply I must have been doing it really wrong, even though I was getting partial results. Well this is truly a gift and thank you so very much for your detailed example.

    Tuesday, September 15, 2020 3:26 PM