I've got the following property in the code-behind of my .aspx:
protected string CurrentProductView
{
get
{
string viewName = string.Empty;
viewName = Enum.GetName(typeof(ProductView), currentProdView);
return viewName;
}
}
In my .aspx I've got some Javascript that tries to reference this string:
$(document).ready(function ()
{
var action = <%=CurrentProductView %>
$("#recommendations").load("recommendationsHandler.ashx?action=" + action + "item&csid=" + csid + "&productID=" + productID, function()
{
$("#recommendationsView").show();
});
});
but for some reason I get "Item is not defined".
When I debug this, I'm definitely seeing a string come back for viewName. So why would it complain if a string is coming back?!?!
Change this:
var action = <%=CurrentProductView %>
to this:
var action = "<%=CurrentProductView %>"
Since you are printing out a string value to the page into a variable, you need quotes around it, because the value is viewed as a literal value to the JavaScript on the page. You don't need the quotes around ints, because in JavaScript this is legal:
var my_number = 4;
where this is not
var my_string = this is a string;
and it needs to be this:
var my_string = "this is a string";
Related
It's a fairly simple problem, I am using AngularJS v1.7.2 with C# MVC.
I got my standard setup with Layout pages and Views.
I load my AngularJs controllers/services from external script files so there's nothing on the Views.
My problem is that I want to assign a value from ViewBag to a controller variable, but I obviously can't reference ViewBag in a script as it needs to be done on the cshtml page.
I have tried doing it inside ng-init like so
<div ng-init="City = #ViewBag.City"></div>
Or
<div style="visibility: hidden;">{{CityId = '1'}}</div>
I tried variations with {{City = #ViewBag.City}}, '#ViewBag.City' and couple of others I saw on StackOverflow to no avail.
I load my scripts on the view using:
#section Page_Scripts {
#Scripts.Render("~/angular/ngListing")
}
That obviously is loaded in Layout. My controller works fine so that's not the issue.
My controller is making an ajax call upon initialization, at that point I need the $scope.City to be populated with the right value, however it's always set at 0.
Here's what my controller + service (combined for sake of SO) looks like:
_mainApp.controller("ListingCtrl", function ($scope, $http) {
$scope.City = 0;
$scope.Attractions = [];
$scope.Offset = 0;
$scope.Pages = new Array(10);
var MakeRequest = function (offset) {
$http.post("/City/GetStuff?City=" + $scope.City + "&Offset=" + offset).then(function (resp) {
$scope.Attractions = resp.data;
});
}
MakeRequest($scope.Offset);
$scope.PageUp = function () {
$scope.Offset++;
MakeRequest($scope.Offset);
}
$scope.PageDown = function () {
$scope.Offset--;
MakeRequest($scope.Offset);
}
$scope.GoTo = function (offset) {
$scope.Offset = offset;
MakeRequest(offset);
}
});
Any solution that is not hacky-ish would be appreciated. It can include directives or a way to assign a value to $scope.City but inline, or at least get my ViewBag.City value passed to the controller somehow.
Use a function in the ng-init directive:
<div ng-init="initCity(#ViewBag.City)"></div>
Define the function in the controller:
$scope.initCity = function(city) {
$scope.city = city;
MakeRequest($scope.offset, $scope.city);
};
function MakeRequest(offset,city) {
var url = "/City/GetStuff";
var params = {city:city, offset:offset};
var config = {params: params};
$http.get(url,config).then(function (resp) {
$scope.Attractions = resp.data;
});
}
This way the controller will wait for the ng-init directive.
How to return some value from asp.net page that is called using jQuery Get() method ? The get method is given below and i want the alert() should display the returned value.
The get() calls "result.aspx" page that return a string and that string i want to show in alert().
$.get("result.aspx",
{
name: "Donald Duck",
city: "India"
},
function (result, status, xhr) {
alert(result);
}
);
The result.aspx code is:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadReturn();
}
}
void LoadReturn()
{
string name = Request.QueryString["name"];
string city = Request.QueryString["city"];
string returnValue="Hello Mr."+ name + " who lives in " + city;
//How to return value of returnValue to the jquery get() function.
}
How to return value of returnValue to the jquery get() function ??
Update
I tried the response.write(). It is able to return the data to jquery get() method.
Response.Write(returnValue);
Only problem is that it is also sending me the full HTML of the result.aspx page. Which i don't want.
How can i prevent the unnecessary HTML from reaching the jquery get() method?
I solved it by putting Response.End() in the end. Hope it helps others too.
void LoadReturn()
{
string name = Request.QueryString["name"];
string city = Request.QueryString["city"];
string returnValue="Hello Mr."+ name + " who lives in " + city;
Response.Write(returnValue);
Response.End();
}
I'm trying to use a form to load a page with Post data. The post data is an enormous string, and I'm not sure if the length is causing the problem.
I have a search page that directs to a results page, and the results page takes a while to load before showing the results. My client doesn't want the user to be directed away from the search page until the results have finished loading, because they don't like the lengthy "loading" spinner on the results page. The original structure of the site was that when the search button is clicked, it generates a querystring and uses window.location to direct to this action results, which returns a View:
public ActionResult Results(String q, String keywords, int? fromyear, int? toyear, int? newsearch,
String recordtype, String location, int? volumeId, string volumeName, string pageName, IEnumerable<Attribute> attributes,
bool favorites = false, bool free = false, bool images = false,
String firstname = "", String lastname = "", bool soundex = false, bool exact = false, String category = "",
String database = "", String fam1first = "", String fam1last = "", String fam1type = "", String fam2first = "",
String fam2last = "", String fam2type = "", String fam3first = "", String fam3last = "", String fam3type = "",
int size = 50, int page = 1, String sortby = "Relevance", bool accessible = false, bool exactlocation = false, bool loadFirst = false)
{
.......
return View("index", viewModel);
}
I thought I might be able to accomplish this request by splitting the action into two parts: I can use Results to return the viewmodel as json, and then create a new actionresult that takes a json string, deserializes it into the viewmodel, and displays the viewmodel on the page:
public ActionResult LoadedResults(String jsonString = "")
{
var vm = JsonConvert.DeserializeObject<SearchResultsViewModel>(jsonString);
return View("index", vm);
}
Now, on my search page, instead of navigating directly to a new URL, I do this:
var searchUrl = window.location.protocol + "//" + window.location.host + "/SearchResults/Results?" + querystring;
$.ajax({
url: searchUrl,
type: 'GET',
dataType: 'json',
success: function (info) {
console.log(info);
var results = JSON.stringify(info);
$("#jsonString").val(results);
$("#submitResults").click();
},
error: function (info) {
alert("error");
}
with this form:
<form id="resultsForm" method="POST" action="http://nehgs.mvc/SearchResults/LoadedResults">
<input type="text" name="jsonString" id="jsonString"/>
<br/>
<input type="submit" value="Submit" id="submitResults"/>
</form>
However, submitting the viewmodel string is leading to an error page with no information about what caused the error. I put a breakpoint on the first line of the LoadedResults actionresult. When I click the submit button with nothing in the text box, I hit the breakpoint. I also hit the breakpoint when I put in a dummy string, like "hello!", or empty json, like "{}". However, when I put in my actual viewmodel string, the breakpoint doesn't get hit, I just immediately get an error page.
Is this because my viewmodel string is too big? The string I'm testing with is 63088 characters, and it varies depending on the search. If this is the reason it's not working, is there any way that I can accomplish what my client is asking?
In your code use
$('#resultsForm').submit(function(event){
event.preventDefault();
$.ajax({
type:"post",
data:$(this).serialize(),
success:function(response){
//Your Code.
}
});
});
This will send the Form data using Post Method and you can load the result in the new page.
This is how i pass value to the page called in iframe
<script type="text/javascript">
function refreshConversatio() {
document.getElementById('ifrmConversation').src = 'Default2.aspx?id=' + document.getElementById('<%=HiddenField1.ClientID %>').value;
}
</script>
This is How i recieve value in othe page which is being loaded in iframe
<script type="text/javascript">
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, " "));
}
function myLoad() {
document.getElementById('<%=hdn.ClientID%>').Value = getParameterByName("id");
}
</script>
<asp:HiddenField ID="hdn" runat="server" />
<script type="text/javascript">
myLoad();
</script>
I think that there is problem somewhere (might be in myLoad() ) because i am not able to recieve passed value. What am i doing wrong here?
Please refer this SO answer to know how to call a function in iframe from parent window:
Calling javascript function in iframe
In order to get the value of hidden field try the following:
var abc = document.getElementById('hdn');
or
var abc = document.getElementById('hdn').value;
Try this sample way
code
<asp:HiddenField ID="hf_myhiddenfield" runat="server" Value="hidden value"/>
You can use a Javascript function to insert the value into your onclick attribute
onclick
onclick="window.open('../New/FeedbackV4.aspx'+GetHFValue(),'FeedbackWindow','width=960,height=640,scrollbars=yes,resizable=yes,status=yes')"
Javascript
<script type="text/javascript">
function GetHFValue() {
var hf_value = '?' + document.getElementById("<%= hf_myhiddenfield.ClientID %>").value;
return hf_value;
}
</script>
The above code sample is here
and Call this below code for get query string value
/*
* <summary>
* Get the querystring value
* </summary>
* <param name="key">A string contains the querystring key</param>
* <param name="defaultVal">Object which get returns when there is not key</param>
**/
function getQuerystring(key, defaultVal) {
if (defaultVal == null) {
defaultVal = "";
}
key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
var qs = regex.exec(window.location.href);
if (qs == null) {
return defaultVal;
}
else {
return qs[1];
}
}
Is there a way to add a Html.ActionLink through javascript?
For instance, I have this Edit function in my controller:
public ViewResult Edit(int companyID)
{
....
}
And I'd like to do something like this in javascript:
var id = $("#hdnID").val();
$("#editLink").html(<%: Html.ActionLink("Edit", "Edit", new { id }) %>);
A bit of a crude example, but it's basically what I'd like to do. Is it at all possible?
The id is a client script. You cannot mix server side script with client script. I am afraid that you are trying to submit HTML forms with action links instead of using submit buttons which is very bad. I see that you fetch the value of an input field with $("#hdnID").val() and then try to assign it to some action link and send to the server whereas if you used a simple submit button you wouldn't even need javascript. Your code would simply be:
<% using (Html.BeginForm("Edit", "Home")) { %>
<%: Html.HiddenFor(x => x.HdnId) %>
<input type="submit" value="Edit" />
<% } %>
Also it is clear that if you are using a hidden field it's because the user cannot change the value so an even simpler solution would be to directly generate the link you need:
<%: Html.ActionLink("Edit", "Edit", new { id = Model.SomeId }) %>
I haven't found a really good way yet. What I usually do is something like this:
var id = $("#hdnID").val();
var link = '<%: Html.ActionLink("Edit", "Edit", new { id = -999 }) %>';
$("#editLink").html(link.replace('-999', id));
The key is to select a value that id would never have in reality or exist otherwise in the link.
I found a handy way out of this problem thinking slighly out of the box. The reason I use ActionLink is really for an easy way to handle the routing. Simply supply Controller and action name and the helper generates the correct url. To get around this in JavaScript I first created an HtmlHelperExtender using the UrlHelper to resolve the url in proper context.
namespace System.Web.Mvc.Html
{
public static class HtmlHelperExtensions
{
public static string ResolveUrl(this HtmlHelper html, string url)
{
var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
return urlHelper.Content(url);
}
}
}
Now in JavaScript it's easy enough to get the proper Url
$(document).ready(function () {
var action = '<%= Html.ResolveUrl("~/Controller/JsonAction") %>';
// JSON controller call for model data
$.getJSON(action, null, function (models) {
// Do something with models
action = '<%= Html.ResolveUrl("~/Controller/Details/") %>';
for (var i = 0; i < models.length; i++) {
$('#modelList').append(
'<tr><td>' + models[i].Title + '</td></tr>');
}
});
});
This is how I did it. You can use javascript replace.
var ul = document.createElement('ul');
if (data.EvidenceList != null) {
for (var i = 0; i < data.EvidenceList.length; i++) {
var li = document.createElement("li");
var evidenceId = data.EvidenceList[i].EvidenceId;
var evidenceName = data.EvidenceList[i].Name;
var candidateProgrammeComponentId = data.CandidateProgrammeComponentId;
var str1 = '#Html.ActionLink("dummyEvidenceText", "DownloadFile", new { candidateProgrammeComponentId = "dummyCandidateProgrammeComponentId", evidenceId = "dummyEvidenceId", evidenceName = "dummyEvidenceName" })';
var str2 = str1.replace('dummyEvidenceName', evidenceName);
var str3 = str2.replace('dummyCandidateProgrammeComponentId', candidateProgrammeComponentId);
var str4 = str3.replace('dummyEvidenceId', evidenceId);
var str5 = str4.replace('dummyEvidenceText', evidenceName);
li.innerHTML = li.innerHTML +str5 ;
ul.appendChild(li);
}
}
var element = document.getElementById('evidenceList_' + data.guidId);
$('#evidenceList_' + data.guidId).empty();
document.getElementById('fileUploadFreeStructure_' + data.guidId).value = '';
$('#freeTextArea_' + data.guidId).val('');
element.appendChild(ul);
The server side code (the C#) is ran on the server, and the result is sent to the client, where the client then executes the JavaScript. So as weird as it is, you have two different code environments bumping into each other but can't interact with each other very well.
I usually do something like this, although I'm open to better ways:
function SetUrl(id) {
var url = '<%: Html.ActionLink("Bar", "Foo") %>' + '?id=' + id;
return url;
}
This takes advantage of the fact that
/Foo/Bar/{id} is usually equivalent to /Foo/Bar?id={id}, depending on how your routes are set up.