0

I have two views (create/edit) that require the same javascript for client-side functions. I want to place my javascript into a separate file so I can reference/reuse the script on both my views but I cannot do this because I am using MVC extension methods in my javascript.

For example:

$.ajax({
    type: 'GET',
    url: '@Url.Action(MVC.Attribute.GetTargetedOrganisationAttributeScope())',
    traditional: true,
    data: { organisationIDs: ids },
    success: function(data) {
            // ...
        }
    }
});

One method I found was to place my javascript in a partial view and reference that as it allows me to use MVC extensions. Is this the correct method? Is there a better way of achieving this?

@section Scripts{
    @{
        Html.RenderPartial(MVC.Attribute.Views.ViewNames._js);
    }
}
mr.coffee
  • 962
  • 8
  • 22
  • 1
    I would probably load the cshtml page with a javascript variable holding the value for the url then just use that value in the javascript. – nurdyguy Feb 28 '19 at 22:26

1 Answers1

-2

View

function BuscarPaciente() {

        var identificacion = $("#identificacion").val();
            $.ajax({
                url: "@Url.Action("BuscarDatos")",
                data: { identificacion: identificacion },
                type: "POST",
                success: function(response) {
                    $("#resultado").hide("slow", function() {
                        $(this).html(response);
                        $(this).show("slow");
                    });
                }
            });
    };

Controller

public ActionResult BuscarDatos(string identificacion) {

        CAPBAS capbas = db.CAPBAS.SingleOrDefault(c => c.MPCedu == identificacion);
        return PartialView("DatosUsuario", capbas);

 }
  • 1
    To do this he would have to put that script in the view but he wants to put it in a javascript file. – nurdyguy Feb 28 '19 at 22:27
  • what you are looking for is to execute a razor syntax in a javascript file https://code.i-harness.com/es/q/789405, I hope it helps you. – Heiner Said Feb 28 '19 at 22:51