0

I'm having serious trouble trying to include javascript in a Partial View with asp mvc 4, reading this post I followed the instructions to create a custom Html helper to include the js. Unfortunately, either I call it from the layout, and then the method to actually include the Javascript is never called on time (meaning that the page request has already been called when I do the ajax request) or I try to include it in my Partial View, but partial views seem to automatically strip down any javascript written in them. So I tried to render a standard View, but even that hasn't solved the problem. The thing is then, is it even possible to render javascript in a view called with ajax in asp mvc? Has someone done it, please advice. I actually need to run javascript inside my "ajax called" view because I have to detect the values inside a form that is inside that view. I won't post the code of the Helper because it's entirely from the post referenced. Thanks!

Ok I'll try to be more specific as why I think I need the javascript in my particular view. The following is the code of the main view:

    @model MvcCursosSSP.Models.CursosModel
@using System.Threading;
@{

    ViewBag.Title = "AgregarHorario";
    Layout = "~/Views/Shared/_Layout.cshtml";
    int numhoras = ViewBag.NumeroHoras;
    int dias = ViewBag.Dias;
    System.Globalization.CultureInfo culture = Thread.CurrentThread.CurrentCulture;
}

<h2>AgregarHorario</h2>
<table class="horario">
    <colgroup>
        <col id="col1">
        <col id="col2">
        <col id="col3">
        <col id="col4">
        <col id="col5">
        <col id="col6">
    </colgroup>
    <caption>@if (ViewBag.Modulo != null)
             {
                 <text>Modulo </text>@ViewBag.Modulo[0].NumModulo.ToString()<br />@ViewBag.Modulo[0].Nombre.ToString()<br />
             }Horario del @Model.FechaInicio.Day.ToString() de @Model.FechaInicio.ToString("MMMM", culture) al @Model.FechaTermino.Day.ToString() de @Model.FechaTermino.ToString("MMMM", culture)</caption>
    <thead>
        <tr><th>Horario</th>
        @for (int i = 0; i <= @dias; i++)
        {
            <th>@Model.FechaInicio.AddDays(i).ToString("dddd", culture)&nbsp;@Model.FechaInicio.AddDays(i).Day.ToString()</th>
        }
        </tr>
        </thead>
        <tbody>
            @for (int i = 0; i <= @numhoras; i++)
            {
                var newTime = @Model.HorarioInicio.Add(new TimeSpan(i, 0, 0));
                <tr><td>@newTime.Hours:00</td>@for (int j = 0; j <= @dias; j++)
                                                 {
                                                 <td id="@newTime.Hours" rel="@Model.FechaInicio.AddDays(j).Day.ToString()"><span class="addHorario">AgregarHorario</span></td>
                                                 }
                </tr>
            } 
        </tbody>
    </thead>
    </table>
@section scripts {
<script type="text/javascript">
    $('span.addHorario').click(function () {
        var td = $(this).parent('td');
        td.load("/Cursos/CreateMateria/" + new Date(@Model.FechaInicio.Year.ToString(), @Model.FechaInicio.Month.ToString(), td.attr('rel')).toISOString().substring(0,10) + '/' + td.attr('id'));
    });
    $('button[id^="save"]').click(function () {
        horaini = $('#horarioInicio'+$(this).attr('id').substring(4, $(this).attr('id').length)).val();
        horafin = $('#horarioFin'+$(this).attr('id').substring(4, $(this).attr('id').length)).val();
        alert(parseInt(horafin)-parseInt(horaini));
    });
</script>
}

But the final javascript starting with the line: $('button[id^="save"]').click is not working, I think because the dom has already been built and jquery isn't recognizing anything. Can someone suggest a solution?

5
  • Scripts should in the main view or layout, not in a partial view, but why do you think you need a html helper for this? Commented Mar 2, 2015 at 2:17
  • Sorry read the following comment, I tried to edit this one but I finally posted another one. The thing I wonder is how to run the javascript when the dom has already changed due to the ajax call? Commented Mar 2, 2015 at 2:40
  • I have setup a fiddle to illustrate this [link]jsfiddle.net/t97Lue3m/2 I think I need the javascript to run in my partial view for it to run correctly, otherwise the call to document.ready already had past. Am I wrong? Commented Mar 2, 2015 at 2:41
  • If your main view has an ajax function to dynamically load a partial view, then you use event delegation, e.g. $(document).on('click', '#someElement', function() { // do something }); Ideally, replace document with the closest ancestor which exists at the time you first render the view, and #someElement could be .someClassName in your case (rather than 'button[id^="save"]') Commented Mar 2, 2015 at 2:56
  • Sorry it seems like you were thinking the same thing as I was posting my answer. Nobody stole anyone's idea though. I did as you said. Thank you :) Commented Mar 2, 2015 at 2:59

1 Answer 1

0

Nevermind, I solved it. I looks like Jquery already has the solution to this, simply by adding a callback function to the load like so:

$('span.addHorario').click(function () {
    var td = $(this).parent('td');
    td.load("/Cursos/CreateMateria/" + new Date(@Model.FechaInicio.Year.ToString(), @Model.FechaInicio.Month.ToString(), td.attr('rel')).toISOString().substring(0,10) + '/' + td.attr('id'), function(){
        $('button[id^="save"]').click(function () {
            horaini = $('#horarioInicio'+$(this).attr('id').substring(4, $(this).attr('id').length)).val();
            horafin = $('#horarioFin'+$(this).attr('id').substring(4, $(this).attr('id').length)).val();
            alert(parseInt(horafin)-parseInt(horaini));
        });   
    });
});

and now I can manipulate the dom of my partial view. Thanks!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.