Javascript reuse with ASP.NET MVC extensions

196 Views Asked by At

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);
    }
}
1

There are 1 best solutions below

2
Heiner Said On

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);

 }