Passing parameters to actionresult with javascript

时间:2016-04-04 18:49:29

标签: javascript asp.net-mvc-5 query-string

I'm using this on a button's onclick to trigger a ActionResult

function update(element) {
            var form = $(element).closest('form');
            form.attr('action', "@Url.Action("CompanyUpdate")");
            form.attr('data-ajax-method', "POST");
            //form.attr('data-ajax-update', "#ajax-target");
            form.submit();
        }

But I'm having problems with sending a parameter, an url parameter to ActionResult.

my url seems like this now

....Admin/Registration/AdminCompanySettings?Id=98

and I can succesfully take the id parameter out of it with another javascript function. I'm stuck at sending it to ActionResult. How can I manage it?

I recently started all these and don't know if JS is right way to go

EDIT:

My ActionResult is like this

public ActionResult CompanyUserAdd(Ebelge.ViewModels.AdminCompanySettingViewModel CompanyInfo)
        {
           //stuff inside
        }

I was planning to get the url parameter inside it via

int CompanyId = Convert.ToInt32(Request["Id"]);

EDIT 2:

I'm trying something like this now. I put the js function which I get the parameters from url inside my update function but it gives "Id doesn't exist in current content" error.

function update(element) {

             var getUrlParameter = function getUrlParameter(sParam) {
                 var sPageURL = decodeURIComponent(window.location.search.substring(1)),
                     sURLVariables = sPageURL.split('&'),
                     sParameterName,
                     i;

                 for (i = 0; i < sURLVariables.length; i++) {
                     sParameterName = sURLVariables[i].split('=');

                     if (sParameterName[0] === sParam) {
                         return sParameterName[1] === undefined ? true : sParameterName[1];
                     }
                 }
             };

             var Id = getUrlParameter('Id');


            var form = $(element).closest('form');
            form.attr('action', "@Url.Action("CompanyUpdate", new RouteValueDictionary(new { Id = Id}) )");
            form.attr('data-ajax-method', "POST");
            //form.attr('data-ajax-update', "#ajax-target");
            form.submit();
        }

0 个答案:

没有答案