1

I want to be able to pass the string output of my javascript function as a parameter to my MVC 4 Razor Url Action which itself is passed as a custom attribute to the input element. Here is the razor in my view file:

@Html.TextBoxFor(model => model.SomeProperty, new{data_autocomplete = @Url.Action("SomeAction","SomeController", new { someParameter= "here I want the string output of my javascript function" })})

How can I possibly achieve this?

Pejman
  • 3,784
  • 4
  • 24
  • 33

2 Answers2

1

I believe this could be done only after the HTML is rendered. The reason behind this is the Razor is mainly used for rendering the HTML. The Javascript could be run upon for a HTML element only its is completely rendered. If I understood your question, you want to dynamically assign the URL which is rendered by the javascript function to the data_autocomplete property of the textbox. I would suggest you the method below

var currentURL = @Url.Action("SomeAction","SomeController");

var parameters  = YourJSMethodToreturnTheParameterValue();

$("#SomeProperty").attr("data_autocomplete",currentURL+'?someParameter='+parameters;

Ideally, the TextBoxFor would render the Property name as its ID.

clklachu
  • 951
  • 1
  • 7
  • 19
  • Well, thanks for the reply. I did it but it seems the js added parameter isn't passed to the action. It is null when I break point it! – Pejman Dec 03 '12 at 10:05
  • One point: Just ensure if the action has the parameter with same name and query string param? Can you please post your sample script and the action method ? – clklachu Dec 03 '12 at 10:44
0

Try this:

var textbox = document.getElementById('SomeProperty');
var currentUrl = textbox.getAttribute('data_autocomplete');
currentUrl  += '?someParameter=' + myJsFunctionThatReturnsString();
textbox.setAttribute('data_autocomplete', currentUrl);
karaxuna
  • 26,752
  • 13
  • 82
  • 117