I am programatically reading data from a text input using standard Jquery like this:
var listName = $('#list').val();
and then I am adding a hidden input field into a form before submitting like this:
var myForm = $("#myForm);
myForm.append('<input type="hidden" name="List" value="' + listName + '" />');
In one example, the value in the field is:
Key Date & Times
so on the UI it looks like this
<input type="hidden" name="MyList" value="Key Date & Times" />
when I submit the form using:
var myForm = $("#myForm);
myForm.submit();
and check it on the asp.net-mvc server side i only see:
Key Date
being sent over. After some research, it was suggested to write some javascript to run the value through:
encodeURIComponent()
After doing that and taking a look at the server side, I now see:
Key%20Date%20%26%20Times
How can I convert that back to
Key Date & Times
on the C# asp.net-mvc server side? Or Seperately, if I am doing something wrong on the client side, please let me if you have any suggestions.
My main question is why do i have to worry about encoding the value of a hidden input box in a form. I would have thought this would be taken care of for you.
string decodeString = HttpUtility.UrlDecode(@"Key%20Date%20%26%20Times");
Use UrlDecode
method of HttpUtility
class.
There's something wrong on client-side. I've tested the following code which is like one you wrote and worked fine!
<input type="hidden" id="ref" value="Key Date & Times" />
<form id="form1" action="~/home/handle" method="post">
<input type="submit" />
</form>
<script>
var myForm = $('#form1');
var listName = $('#ref').val();
myForm.append('<input type="hidden" name="name" value="' + listName + '" />');
</script>
You have no need to use conversion tools!
I think no need to do any thing with your code, it works properly, i have folow below code, please confirm it.
View/Html:
@using (@Html.BeginForm("Save", "Home", FormMethod.Post, new { id = "myForm", name = "myForm" }))
{
<input type="button" class="btn btn-danger" value="Click" id="btnClick">
}
Jquery:
$(document).ready(function () {
var myForm = $("#myForm");
myForm.append('<input type="hidden" name="List" value="Key Date & Times" />');
$('#btnClick').click(function () {
var myForm = $("#myForm");
myForm.submit();
});
});
Controller:
public ActionResult Save()
{
return RedirectToAction("Index");
}
Output:
this happens when you use GET method to submit a form (in GET method '&' acts as a variable separator) you have to use POST method or String manipulation.
if you are using encodeURIComponent()
you can convert it back using Server.UrlDecode("");
on server side
you can also read this for extra knowledge Click here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With