Elliot Naylor Elliot Naylor - 23 days ago 11
C# Question

Populating global variable in razor view using JQuery (MVC)

Please see code below:

@{
var propertyList = new List<Tuple<string, string>>();
}

<input type="text" data-id="@item.Item1" class="form-control prop"/>

<a class="btn btn-default" id="run-report" href="@Url.Action("RunReport", "Reports", new {reportId = Model.ReportId, propList = propertyList})"> Run Report</a>

<script>
$("#run-report").click(function () {
$(".prop").each(function () {
var currentProp = $(this).attr("data-id");
var currentPropVal = (this).value;

@{
propertyList.Add(new Tuple<string, string>("", ""));
}

});
});

</script>


As you can see above, I have a global variable called
propertyList
containing a list of tuples,
<string, string>
.

I declare this here because I need to use the
Url.Action
to download a report direct to the browser from my controller action.

I have hit a bit of a wall when I get the values from my text box. I need to add the values from my jQuery to my global list of tuples.

It doesn't look like I can do it this way.

Any advice would be much appreciated!

Thanks

Answer

Remember that @{} code runs server-side, so before it gets to the browser. Once it has "rendered" in the browser, it's as if it was plain text and can't be changed.

You can pass your parameters by building them in the script, eg:

Remove the param from the Url.Action arguments

<input type="text" data-id="@item.Item1" class="form-control prop"/>
<a class="btn btn-default" id="run-report" href="@Url.Action("RunReport", "Reports", new {reportId = Model.ReportId})"> Run Report</a>

Add them via script

$("#run-report").click(function () {

    var url = $(this).attr("href");

    $(".prop").each(function () {
        var currentProp = $(this).data("id");
        var currentPropVal = (this).value;

        url += "?" + currentProp + "=" + currentPropVal;
    });

    location.href = url;
});

Depending on the format expected by your action, you may need to change how your url is built, but this shows the principle.

Comments