setting the value of textbox equal to address bar in MVC4? - c#

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.

Related

Capture value of Textbox when OnChange is defined in the textbox

I have a dynamically generated grid with x number of textboxes that will be in it. As each textbox is generated, I give it an OnChange event that is a set function.
Html.TextBox(... new { #onchange = "ChangeItemQuantity(" + vm.ID + ", " + fk.id + ")" ...
So when it's rendered, it looks like this:
<input ... type="text" onchange="ChangeItemQuantity(1939, 3)" />
Then, in the script section:
function ChangeItemQuantity(ItemId, ForeignKeyId) {
...
}
In the ChangeItemQuantity() function, how would I also capture the new value of the textbox? I don't really want to use an id on the textbox, because it is part of a grid with many textboxes.
Should I pass it in as a parameter? If so, what would the syntax be of the code that renders the textbox?
Or, is there a way to capture is inside the javascript function?
Thanks!
If you want to store data in the html element why not use data- attributes?
Set them like so
#Html.TextBox(.... new { #class="someClass" data-vmId="vm.ID", data-fkId="fk.id" })
Then set a listener on that class
$('.someClass').change(function() {
var value = $(this).val();
var vmid = $(this).data('vmid');
var fkid = $(this).data('fkid');
}

How Can DeActivate Razor Html Encoding ?

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.

ASP.Net MVC EditorTemplate wrong Id

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.

Pass hidden ID when textbox is changed

I have multiple textboxes, every textbox has a related hidden field, the hidden field's ID is a concatenation of a string with the model's ID (ex: "FormState25")
How can I pass the ID of a hidden field when a textbox being changed? I'm using the following code to detect textbox change:
$("#body-content-container").on('change', 'input[type="text"]', function () {
$("#FormState").val('dirty');
});
You can add custom attributes to the textbox tag itself that includes the Id of the hidden field, for example:
In View
#Html.TextBoxFor(model => model.Name, new { HiddenFieldId = "FormState" + Model.Id })
This way when a textbox get changed you can get the Id of the hidden field you already use to store whatever you want, and then modify the javascript to handle that hidden field's Id, like this:
Javascript
$("#body-content-container").on('change', 'input[type="text"]', function () {
var hiddenId = $(this).attr("HiddenFieldId");
$("#" + hiddenId).val('dirty');
});
The javascript will get the HiddenFieldId attribute of the corresponding hidden field from the textbox and change it's value. Try this and let me know..
You can use this to reference the element on which the anonymous function is defined, e.g.:
$("#body-content-container").on('change', 'input[type="text"]', function () {
$("#FormState" + this.attr('id')).val('dirty');
});
try this:
$("input[type=text]").click(function(){
var hiddenId = "FormState" + $(this).attr("Id");
var hiddenField = $("#" + hiddenId);
hiddenField.val("dirty");
});
EDIT:
if your hidden field rendered just after your inputbox then you can do the following :
$("input[type=text]").click(function(){
var hiddenField = $(this).next();
hiddenField.val("dirty");
});
hope this could help.
Here's another trick which I've used in the past. Enclose the two related input fields in a div (or other) element. Then use the fact that the text field and the hidden field are siblings to select the correct hidden field. Perhaps something like this (NOTE: I have not tested this example):
<div id="someId">
<input type="hidden" value="unchanged" />
<input type="text" value="some data" />
</div>
<script type="text/javascript">
var hiddenInput = $('#someId input:first')
var textInput = $('#someId input:last')
textInput.on('change', function() {
hiddenInput.val('modified');
});
</script>

How can I compare a value from C# Viewbag in Javascript?

I want to compare a boolean value from the Viewbag in javascript. So at first I tried this:
if (#Viewbag.MyBoolValue)
do_sth();
But then I have error in console like: Value False/True is not declared (not exactly).
So I tried this:
#{
string myBool = ((bool)Viewbag.MyBoolValue) ? "true" : "false";
}
and in javascript:
if (#myBool == "true")
do_sth();
But it does not work too. How can I make it work? Any help would be appreciated.
What you have should work, assuming that the value from the ViewBag is of a type which javascript can understand.
Note however, that your first example most likely did not work because boolean values are lowercase in javascript and uppercase in C#. With that in mind, try this:
var myBoolValue = #ViewBag.MyBoolValue.ToString().ToLower();
if (myBoolValue)
do_sth();
The below will create a javascript vailable with value from viewbag
<script>
var myBoolInJs = #Viewbag.MyBoolValue;
if(myBoolInJs == true)
do_sth();
</script>
var myBoolVal = #((ViewBag.MyBoolValue ?? false).ToString().ToLower());
or
var myBoolVal = '#(ViewBag.MyBoolValue)'==='#true';
or
var myBoolVal = #(Json.Encode(ViewBag.MyBoolValue ?? false));
This will work.
#{
string myBool = Viewbag.MyBoolValue.ToString().ToLower();
}
if (#myBool)
do_sth();
Insted true and false use 0 and 1 in your controller, on top of razor page
#{
var isSomething= Viewbag.MyBoolValue;
}
Later down
if (#isSomething== 0)

Categories