I have a controller method that returns image from MongoDB, and I want to show it in my view:
<HttpPost()>
Function ShowImage(cardNumber As String) As FileContentResult
Dim Handler = New MongoDBHandler()
Dim newString = cardNumber.Replace(vbLf, "").Trim().Replace("""", String.Empty)
Dim byteArray = Handler.ReadImage(newString)
Return File(byteArray, "image/png")
End Function
I have the javascript function:
function postCardNumber(elm) {
var CardNumber = $(elm).closest("tr").find(".card-number").html();
var $img = $('<img>');
$img.attr('src', "data:image;base64," + #Html.Action("ShowImage", "CreditCard", CardNumber));
$("#myModal").append($img);
}
But there is a red underline under "CardNumber" parameter for the attr function.
Why?
Are you sure that razor templates works with JavaScript? You can translate your razor syntax to js/HTML. But I'm not sure that its works vice-versa. Razor syntax transpiled when your page rendered by the server,js starts working when page loaded. You should rewrite your code to js without using razor in this way
Related
The ultimate goal here is to populate fields of a Bootstrap modal from an object in the C# code behind that has all the data I need. I serialized the object from the code behind, like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
sJSON = serializer.Serialize(aerationsystem.AerationSystem);
Now I want to reference that JSON in my Javascript function, like this:
</form>
<script type="text/javascript">
function fillModal() {
var diameterValue = document.getElementById('diameter');
var aeration = <%# sJSON %>;
diameterValue.innerText = aeration.dBinDiameter;
}
</script>
</asp:Content>
(I included that closing form tag and the closing asp:Content tag so you all could see where it was that I put this Javascript: at the very end of the file.)
However, when I call that Javascript function, this is what I see in the browser's debugger:
<script type="text/javascript">
function fillModal() {
var diameterValue = document.getElementById('diameter');
var aeration = ;
diameterValue.innerText = aeration.dBinDiameter;
}
</script>
I got the idea from here: Any way to pass an object from c# code behind to javascript?
But, the means of accessing that JSON variable does not work for me. I've tried moving my script, but when I do that, I get an error that says "The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).". And I've tried other delimiters, like <%= %>, but I get the same errors depending on script placement. What am I doing wrong? How can I get that JSON string to show up in my Javascript function?
<%# %> syntax is for binding data from data source.
The easiest way is to use a Literal Server Control. It seems a bit weird inside script tag, but it does the job.
<script type="text/javascript">
function fillModal() {
var diameterValue = document.getElementById('diameter');
var aeration = <asp:Literal id="JsonLiteral" runat="server"/>;
diameterValue.innerText = aeration.dBinDiameter;
}
</script>
Code Behind
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonLiteral.Text = serializer.Serialize(aerationsystem.AerationSystem);
<%# %> is a binding block so you need call the Page.DataBind() method, whether in the Page_Load or the Page_PreRender event.
You also need to curate the string so the JSON text doesn't break your javascript:
var aeration = '<%# sJSON.Replace("'", "\'").Replace("\n", " ") %>';
thank you so much for taking the time to answer my question! I ended up solving the problem, with some inspiration from you all. Instead of using a Literal control, I ended up using a <asp:HiddenField> control on the page to store the value. Then, I pulled that its value into the Javascript variable.
The hidden field: <asp:HiddenField ID="JsonLiteral" runat="server" />
The code in the event that assigned the value:
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonLiteral.Value = serializer.Serialize(aerationsystem.AerationSystem);
And the JavaScript that finished the job:
function fillModal()
{
$(document).ready(function () {
var diameter = document.getElementById('diameter');
var control = document.getElementById('<%= JsonLiteral.ClientID%>');
var aeration = JSON.parse(control.value);
diameter.innerText = aeration.dBinDiameter;
});
}
(There's gonna be a lot more to it than just that one property, of course.)
Again, thank you all for you help, because I could not have done it without you!
I have a javascript function and when it is called I want to insert a partial into a div. All is working fine, but, when I want to pass some javascript into Html.Partial ViewDataDictionary, it isn't passing the rendered javascript.
<script>
function addExperience() {
#{var uid = #MvcHtmlString.Create("new Date().getTime()");}
console.info(#uid); //output ok !
var partialView = #(Html.Raw(JsonConvert.SerializeObject(Html.Partial("~/Views/Dashboard/_editUserExperience.cshtml", Model, new ViewDataDictionary { { "id", uid } }).ToString().Trim('"'))))
$("#newExperienceSection").append(partialView); //it renders "new Date().getTime(), not the number
}
</script>
Thank you !
If you call Jsonconvert.SerializeObject with a string (Html.Partial returns a string), it returns a string.
So you statement
var partialView = ... will be rendered as
var partialView = "the contents of the partial view";
That's why, when you do this:
$("#newExperienceSection").append(partialView);
it actually displays the javascript as text.
If you want to get a partial view to execute javascript, you can return javascript inside script tags, and as soon as you add that to the DOM it gets executed, for example if you set your _editUserExperience.cshtml as this:
<script>
alert('this gets executed as soon as you do add this to the DOM with the jQuery append command');
</script>
When you execute $("#newExperienceSection").append(partialView); you'll see the alert.
An easier way to insert a partial view is to take advantage of $.ajax, for example, in addExperience:
$.get('#Url.Action("ActionMethodThatReturnsPartial", "YourController")').done(function(theHtmlReturned) {
$("#newExperienceSection").html(theHtmlReturned);
});
($.get is just shorthand for $.ajax using a get request)
Source: http://api.jquery.com/jquery.ajax/
http://api.jquery.com/jquery.get/
http://api.jquery.com/category/deferred-object/
I have this rows of c# code in View razor page:
#{
List<UserContact> userContacts = ViewBag.contacts;
String contacts = Html.Partial("~/Views/Shared/Contacts.cshtml", userContacts).ToHtmlString();
}
I want to use the content of contacts variable in JavaScript function since the contacts is a C# object I cant use this variable in JavaScript function.
Is there any way to use contacts variable in Javascript function?
Maybe since the type is string it can be converted to JavaScript variable?
You can use # directives like you would normally do. You can print it using Html.Raw:
var x = /* this is javascript */
#{
...
#Html.Raw(contacts)
}
Or just call #Html.Partial directly:
var x = /* this is javascript */
#{
...
#Html.Partial(...)
}
Or declare it here:
#{
...
string contacts = #Html.Partial(...)
}
And use it later:
#contacts
Yes there is, you only need to render it inside a script block. Try this:
<script>
var contacts = '#contacts';
alert(contacts);
</script>
Within a <script> tag in a jsp file I have some code that looks like this:
var chart = new myChart({'id': ${user.id}, 'type': ${user.type}, 'name': {user.name});
Where user is a Spring model attribute set on the server side. My problem is that passing each different field of user feels clunky. It would be nice if I could do something like this:
var chart = new myChart('user': "${user}");
However when done this way the value of ${user} will be an object string that looks like this:
User{id=1, type='admin', name='foo'}
I know that I could just parse this string into an object in my external js, but it feels like there should be a cleaner way to do this. Thanks for the help.
EDIT: Going off of Cameron's answer below I could add this to my server-side controller code:
model.put("user", user);
String userJSON = MyJSONSerializer.serialize(user);
model.put("userJSON", userJSON);
Then in my JSP I could do:
var chart = new myChart({'user': JSON.parse('${userJSON}')});
This does solve my problem of having a messy options object, but it brings up the issue of using two model attributes for the same exact data. It would be ideal if I could use one model attribute for the user object, and then could somehow encode it to JSON on the fly.
You can convert the Object to JSON using a library like Jackson:
public static String objectAsJSON(Object obj) {
try
{
// This could be optimized by making a static ObjectMapper
return new ObjectMapper().writeValueAsString(obj);
}
catch (IOException e)
{
// Log exception and re-throw or return null
return null;
}
}
You could either call this method before putting the objectin your model and reference the String in your JSP like this:
var chart = ${jsonChart};
Or you could write a custom taglib and call objectAsJSON() from there. Then the actual myChart object could go in your model once. Your JSP might look like:
var chart = <chartlib:toJson obj="${chart}" />;
Should be a simple problem but i dont know exactly why its like this.
In my ASP.NET MVC 5 website i have a simple view with a grid, and a cell action that calls a js function sending some parameters to this function.
function OnCellClick(param1, param2) {
var urlAJAX = #Url.Action("GetJson", "PosicaoEstoque", new { p1 = param1 , p2 =param2}); }
So, like this i get the 'Cannot Resolve symbols' for the param1 and param2.
How can i solve it?
You can use placeholder. Generate url using place holder parameters and then replace them with param
function OnCellClick(param1, param2) {
var urlAJAX = '#Url.Action("GetJson", "PosicaoEstoque", new { p1 = -1 , p2 = -2})';
urlAJAX = urlAJAX.replace('-1', param1).replace('-2', param2);
}
Your problem is that you're mixing server-side and client-side code. You cannot simply put JavaScript variables in Url.Action(), as it runs on the server-side. What you can do is to put some dummy values as parameters and call JavaScript's replace() function on generated URL.
Check this for reference.
Without using Url.Action like below:
var urlAJAX = 'PosicaoEstoque/GetJson?p1=' + param1 + '&p2=' + param2;