In Razor view I have a Javascript function. This function take 2 URLS String in arguments and call AJAX to do operation.
When I generated Url string in Razor, Razor change the URLS. Like changed & to & and damage my query strings which used in my URL address. Also Html.Raw() has not work in this case.
What can I do ?
EXAMPLE:
In my Razor editor:
<a href="#" style="color:#0564c1;" onclick="PopUpStart('POST','','',200,100,'#(Html.Raw(address+"/index/?id="+baseObject.Id+"&"+"type="+dataTypeInt))','#Html.Raw(address + "/cancel/?id="+baseObject.Id+"&type="+dataTypeInt )','ReloadPage',true);return false;">
Edit
</a>
In result :
<a href="#" style="color:#0564c1;" onclick="PopUpStart('POST','','',200,100,'/PdfInstanceEdit/index/?id=1&type=270','/PdfInstanceEdit/cancel/?id=1`&`type=270','ReloadPage',true);return false;">
Edit
</a>
The URL address like :
address+"/index/?id="+baseObject.Id+"&"+"type="+dataTypeInt
Change to :
/PdfInstanceEdit/index/?id=1&type=270
In other world character & => &
Its usually a bad idea to try and combine server code and client strings inside the quotes of a property (ie onclick="something#(something())" )
Its better to just return the entire lot in a server side function
Here's how I would rework your code:
<a href="#" style="color:#0564c1;"
onclick="#Html.Raw(
String.Format(
"PopUpStart('POST','','',200,100,'{0}','{1}','ReloadPage',true);return false;"
, Url.Action("index",address,new{id = baseObject.Id, type = dataTypeInt})
, Url.Action("cancel",address,new{id = baseObject.Id, type = dataTypeInt})
)
)"/>
Edit
</a>
Also note the difference between #(Html.Raw()) and #Html.Raw() - you should use the latter!
As direct assignment of events such as onClick is frowned on these days, a better way to accomplish then may be through js:
Add a hidden field for Id and dataTypeInt to your page:
#Html.HiddenFor(model=> model.Id)
#Html.Hidden("dataTypeInt ", dataTypeInt)
Add an id to your anchor:
Edit
Then your script:
<script>
$(document).ready(function () {
readyLinks();
});
readyLinks = function(){
var id = $('#Id).val();
var dataType = $('#dataTypeInt').val();
var indexUrl = '/PdfInstanceEdit/index?id=' + id + '&type=' + dataType;
var cancelUrl = '/PdfInstanceEdit/cancel?id=' + id + '&type=' + dataType;
$('#editLink).on('click', function(){
PopUpStart('POST','','',200,100,indexUrl, cancelUrl,'ReloadPage',true);
return false;
});
};
</script>
You should use Html.Raw() as suggested in the comments, see the documentation.
As described in this thread, if you have a particular problem with the output encoded format, you could use the HttpUtility.HtmlDecode() function, see documentation.
#Html.Raw(HttpUtility.HtmlDecode(address+"/index/?id="+baseObject.Id+"&"+"type="+dataTypeInt))
But since this could be a solution I cannot address you problem precisely...
A friendly reminder: if you're trying to put a Javascript string inside an HTML attribute, the value must be encoded twice. It must first be Javascript-encoded, then that result must be HTML-encoded. You could inadvertently open an XSS hole in your site if you don't perform both encodings in the correct order.
Say you have a string s that you want to display to the client. You'd write your Razor markup as:
Click me
Note the explicit call to JavaScriptStringEncode. Then Razor's # syntax will auto-HtmlEncode this value before writing it to the response.
Related
How can I get the markup for something I created like this
Div MyDiv = new Div("Test");
I essentially want to get a string with the contents
string SomeString = "<div>Test</div>";
Or maybe even
string SomeString = "<div id="MyDiv">Test</div>;
Is there any way I can do that?
One option is to give the div an id and a runat="server" attribute. If\when the page is posted back to the codebehind, use the InnerHTML property. Example:
<div id="myDiv" runat="server" />
And in your codebehind
string contents = myDiv.InnerHTML;
If you only need this data client side, use javascript, like mentioned in the comments above. You can use the following code:
var x = document.getElementById('myDiv').innerHTML;
If you already have jQuery, then:
var x = $('myDiv').html();
How can I set the Textbox's value equal to address bar?
for example :
localhost:28362/?f=Ava
when we click on a button the value of textbox must set to : Ava
?
Try this, Add Query String Jquery Js(querystring-0.9.0-min.js) in solution
$("#ButtonId").click(function(){
$("#textBoxID").val($.QueryString("f");)
});
Here is Javascript function to get query string value:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Then you need to assign this value to a textbox. I would use jQuery:
$(function(){
$("#myTextBoxID").val(getParam("f"));
})
If you want a solution that uses MVC4 rather than JavaScript, define your controller method as:
public ActionResult Index(string f) {
return View(f);
}
In your view, you would then use one of:
#model string;
#Html.TextBoxFor(Model)
or
#model string
<input type='text' value='#Model' name='myValue' />
Obviously this is vastly oversimplified, but should give you a good starting point.
So I have a double field called Area. I print it this way:
<div>#Html.EditorFor(model => model.Area)</div>
My EditorTemplate for Double looks like this:
#{
var attributes = this.ViewData.ModelMetadata.ContainerType.GetProperty(this.ViewData.ModelMetadata.PropertyName).GetCustomAttributes(true);
var htmlAttributes = GAtec.AgroWeb.Basic.Ux.Web.Helpers.EditorTemplateHelper.GetAllAttributes(ViewData, attributes);
var decimalPlaces = htmlAttributes["data-format"].ToString().Split(',');
var value = decimalPlaces.Length > 1 ? Model.ToString("n" + decimalPlaces[1]) : Model.ToString();
#System.Web.Mvc.Html.InputExtensions.TextBox(this.Html, Html.NameFor(model => model).ToString(), value, htmlAttributes);
}
<script>
$(document).ready(function () {
$("##Html.IdFor(model => model)").restrictNumber();
});
</script>
Nice, but why the html element comes wrong as <input id="Area_Area" /> and the jQuery selector comes right as $("#Area") ?
Both NameFor and IdFor returns "Area" when I watch them on debbuging.
UPDATE:
My htmlAttributes(As #DarinDimitrov asked) returns this array:
["data-min": "0.0", "data-format": "0,2"]
What's the point of stuffing gazilions of inline scripts inside your view (one for each editor template), when you could simply append a class="number" to your input field and then externalize your javascript in a separate file (which is where javascript belongs) and simply use a class selector:
$(document).ready(function () {
$(".number").restrictNumber();
});
#System.Web.Mvc.Html.InputExtensions.TextBox(this.Html, "", value, htmlAttributes);
This resolved my problem. The point is, the MVC knows the model name so you don't have to say him what to print. If you do, it will concat with the model name. But why it does this, I really don't know.
Im a newbie with razor and i having that problem. How can do it?
I need to write an id attribute if a condition has met. Here what I've tried:
<select name="#LabelName" #if(LabelName.Contains("CHECK_STATUS")) { var id = "string\'"; #id }>//it prints string'.
<select name="#LabelName" #if(LabelName.Contains("CHECK_STATUS")) { ViewBag.id = "id='check'"; #ViewBag.id }>//same problem id=&quoute;check&quoute;
Suggestion? I need to print that.
How did you end up in this tag soup (I guess, like everyone else, you didn't use view models)? You have HTML helpers that are designed to generate dropdowns. You know, things like:
#Html.DropDownListFor()
But if you want to continue to swim in the soup you could use the ternary operator to conditionally output the id property:
<select name="#LabelName"#Html.Raw(LabelName.Contains("CHECK_STATUS") ? string.Format(" id=\"{0}\"", id) : "")>
or if the id is in the ViewBag:
<select name="#LabelName"#Html.Raw(LabelName.Contains("CHECK_STATUS") ? string.Format(" id=\"{0}\"", ViewBag.id) : "")>
Notice how you should use the Html.Raw helper to avoid the value being HTML encoded (which is what the # function does by default)
I have a nested ASP.NET ListView, the outer one presenting groups of questions, and the inner one presenting distinct questions within the group. Some of the questions are presented as drop down lists. I want to detect the selected value on change without doing a postback. I have seen lots of references that look like "$(#control).val()" but I need a bit more flexibility.
I am adding the JavaScript in the C# code and it looks like this:
js = string.Format("javaScript:setInputSelectOption('{0}'); return false;", hidSelector.Value);
ddlInputSelectOptions.Attributes.Add("onchange", js);
The resultant aspx file contains this generated code;
<div id='Management_q2'>
<input type="hidden" name="ctl00$body$lstExecutive$ctrl1$hidSelector" id="ctl00_body_lstExecutive_ctrl1_hidSelector" value="Management" />
<select name="ctl00$body$lstExecutive$ctrl1$ddlInputSelectOptions"
id="ctl00_body_lstExecutive_ctrl1_ddlInputSelectOptions"
onchange="javaScript:setInputSelectOption('Management'); return false;">
<option value="0">Not Present</option>
<option selected="selected" value="1">Occasionally</option>
<option value="2">Customarily and Regularly</option>
<option value="3">Constantly</option>
</select>
</div>
My .js file contains this code:
function setInputSelectOption(question) {
var n = $('[id$=' + question + '_q2]>[id$=hidSelector]').val();
var v = $('[id$=' + question + '_q2]>[id$=ddlInputSelectOptions]');
setDDLData(n, v);
}
Using Chrome, I have tried these variants on the "var v = " line with the corresponding results:
$('[id$=' + question + '_q2]>[id$=ddlInputSelectOptions]'):
d.fn.d.init[1] $('[id$=' + question +
'_q2]>[id$=ddlInputSelectOptions]').value: undefined $('[id$=' +
question + '_q2]>[id$=ddlInputSelectOptions]').val(): ""
So I am (yet again) looking for the right incantion to utter to jQuery so that it will return the selected value from the DDL.
I would suggest keeping it simple. Add a data- attribute to the DDL you wish to get the values from. Use jQuery to find the value.
ddl.Attributes.Add("data-ddl","reference");
Then in JS.
// get value
var ddlValue = $("select[data-ddl='reference']").val();
// assign value
$("select[data-ddl='reference']").val("option");
Also, if the JS is only for UI logic, it's best to keep it out of the C# code and run it on the page ready using jQuery. So in your JS file.
$(function(){
// bind a function to the select change event
$("select[data-ddl='reference']").change(function(){
// insert UI logic here
});
});