In my form I have a textbox as below
#Html.TextBox("first_name")
I need to pass the value of this textbox to controller through a actionlink.
I tried the below
#Html.ActionLink("View", "view_Details", new { name = first_name})
but this is giving error
"first_name" does not exist in the current context
Is this possible using a Actionlink?
My controller signature is
public ActionResult view_Details(string name)
{
return View();
}
Edited
#Html.ActionLink("View", "view_Details", new { name = getname()})
<script type="text/javascript">
function getname() {
return $("#first_name").val();
}
</script>
I tried above code. Its also giving error
getname() does not exist in the current context
You need javascript/jquery to get the value of the textbox and then update the url you want to redirect to
Html
#Html.ActionLink("View", "view_Details", new { id = "myLink" }) // add id attribute
Script
$('#myLink').click(function() {
var firstname = $('#first_name').val(); // get the textbox value
var url = $(this).attr('href') + '?name=' + firstname; // build new url
location.href = url; // redirect
return false; // cancel default redirect
});
Side note: further to you edit, the reason you receive that error is that razor code (the #Html.ActionLink() is parsed on the server before its sent to the view but getname() is a client side method which does not exist at that point - i.e it does not exist in the current context
Related
I'm trying to build window.location.href passing a 1 entry query string.
The MVC action method expects that entry to be an integer.
I can hardcode a '2' and it works. Of course I do not want to hardcode.
So I get the value and set a variable and attempt to pass that variable using either of the 2 cases below but it fails. I get:
{0}The parameters dictionary contains a null entry for parameter 'blogCategoryId' of non-nullable type
'System.Int32' for method 'System.Web.Mvc.ActionResult BlogsForMaintIndex(Int32)' in
'GbngWebClient.Controllers.AdminFunctions.BlogMaint.BlogMaintController'. An optional parameter must
be a reference type, a nullable type, or be declared as an optional parameter.
How do I build it properly?
Here is the JavaScript:
$(function () {
$('#buttonClose').on('click', function () {
$('#modalView').modal('hide');
// The action method expects an integer.
var blogCategoryId = #Convert.ToInt32(Session["BlogCategoryId"]);
alert('blogCategoryId: ' + blogCategoryId);
// WORKS!
//window.location.href = "/BlogMaint/BlogsForMaintIndex/?blogCategoryId=2";
// Neither of these 2 work.
//window.location.href = "/BlogMaint/BlogsForMaintIndex/?blogCategoryId=blogCategoryId";
window.location.href = "/BlogMaint/BlogsForMaintIndex/?blogCategoryId=' + blogCategoryId + '";
})
})
Here is the simplified action method:
[HttpGet]
public ActionResult BlogsForMaintIndex(int blogCategoryId)
{
}
Try this
let myurl = "/BlogMaint/BlogsForMaintIndex/?blogCategoryId=" + blogCategoryId;
window.location.href = myurl;
I have a View which calls the function 'Versions' on click of a href, which normally returns a 'Version.cshtml'.
I modified that Controllerfunction:
If i click on that link and JavaScript is enabled, it starts an ajax call which returns a JSON-result. It modifies the DOM so the page won't reload. Now my problem is to differentiate when JavaScript is enabled or not - If enabled, it should return the JSON result; if disabled it should return the 'Version.cshtml'. When I inspect the element, we have already a class called 'nojs-noborder' when JS is disabled. But how can i get that value through the controller without JS so I can fill the bool 'isJavaScriptenabled'?
Controller function looks like this:
if (isJavaScriptEnabled)
{
var tocstr = ControllerContext.RenderView(PartialView("Versiontoc", model));
var middlestr = ControllerContext.RenderView(PartialView("Versionmiddle", model));
var result = new JsonResult
{
Data = new { tocstr, middlestr },
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
MaxJsonLength = MaxValue
};
return result;
}
return View("Version", model);
The class in the inspected element:
<div class="nojs-noborder" id="contentwrapper">
It's unclear from your answer whether you have done this but you need to update your view to make an AJAX request or follow the anchor tag depending on whether JavaScript is enabled or not.
Then, in your controller, you don't need to determine if JavaScript is enabled in the browser, but rather whether the request is an AJAX request. If it is, return JSON else return the view.
Most JavaScript libraries will append the X-Requested-With header with a value of XMLHttpRequest. You can check for the existence of this header.
I'm unsure what version of MVC you are using but you could use the built in Request.IsAjaxRequest() to determine this.
Your ActionMethod then becomes:
if (Request.IsAjaxRequest())
{
var tocstr = ControllerContext.RenderView(PartialView("Versiontoc", model));
var middlestr = ControllerContext.RenderView(PartialView("Versionmiddle", model));
var result = new JsonResult
{
Data = new { tocstr, middlestr },
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
MaxJsonLength = MaxValue
};
return result;
}
return View("Version", model);
If this method isn't available you could roll your own based on this answer
I'm trying to bind this variable on view so i don't need to send it through ajax call, not sure if that is possible but following the logic it looks like it would be.
<script>
$(function ()
{
GetStocksByUAP();
});
function GetStocksByUAP() {
#{
Model.Sector = "UAP1";
}
$.get('/dashboard/Index?handler=StocksBySector', function (response) {
swal('OK', 'Dados carregados', 'success');
console.log(response);
});
}
</script>
cs file
[BindProperty]
public string Sector { get; set; }
public IndexModel(IConfiguration config)
{
_config = config;
}
public async Task<IActionResult> OnGetStocksBySectorAsync()
{
IDbConnection con = new SqlConnection(_config.GetConnectionString("DefaultConnection"));
var result = await con.QueryAsync<DashboardViewModel>("GetStocksByUAP", new { UAP = Sector });
return new JsonResult(result);
}
To summit up, I'm trying to use the string Sector declared on the page and access it's value binded on the view after ajax get request on server. Not sure if this is possible though
If you want to process a value in a handler that gets called by an AJAX request using the GET method, you need to pass the value to the handler. You can do that as a query string value or as a route data value, but either way, it must be passed in the URL.
If you want to bind the value to a PageModel property, you must specify SupportsGet = true in the BindProperty attribute:
[BindProperty(SupportsGet=true)]
public string Sector { get; set; }
See more about how model binding works in Razor Pages here: https://www.learnrazorpages.com/razor-pages/model-binding#binding-data-from-get-requests
I am trying to construct a URL using a HTML helper extension method while trying pass in parameters to the extension method. For example
public static MvcHtmlString GenerateActionLink(this HtmlHelper html,string displayText,string id,int logicstatusId)
{
var actionName = string.Empty;
var controllerName = string.Empty;
if (logicstatusid == 5)
{
actionName = "Basic";
controllerName = "HighBasic";
}
else
{
action = "Advanced";
controllerName = "HighAdvanced";
}
var targetURL = UrlHelper.GenerateUrl("Default", action, controller, new RouteValueDictionary(new { id = id}), RouteTable.Routes, html.ViewContext.RequestContext, false);
//Create the hyper link tag
var anchorLinkBuilder = new TagBuilder("a");
//Merge the target URL with the href attribute
anchorLinkBuilder.MergeAttribute("href", targetURL);
return MvcHtmlString.Create(anchorLinkBuilder.ToString(TagRenderMode.Normal));
}
While this helper method is working, the problem I am facing is on the client side.
var cellHtml = '<div class="action-column">';
var id= row.encryptedId;
cellHtml += '#Html.GenerateHtmlLink("Blip","'+ id+'" , 4)';
cellHtml += "</div>";
return cellHtml;
In this case the URL is getting constructed but the id parameter is not passing on to the helper method. I am not sure if I have done the passing of the parameter the right way. I'd appreciate if anybody help out.
Your C# code (call to the GenerateActionLink helper method) gets executed in server when razor tries to render the view. At that time the js variable value will not be there. The output of razor executing all the C# code view file is just the html markup which the browser will render. Only after that your javascript will be executed and the js variable value will be avaialble.
If you absolutely need to generate the dynamic url (for each id/logicstatusId value) in your client side javascript code using the UrlHelper method, you might consider exposing that C# code via an action method. Whenever you need the link url in your javascript code, make an ajax call to the action method, pass the parameter value and get the url.
public string GenerateActionLink(string id, int logicstatusId)
{
var actionName = "Advanced";
var controllerName = "HighAdvanced";
if (logicstatusId == 5)
{
actionName = "Basic";
controllerName = "HighBasic";
}
var targetUrl = UrlHelper.GenerateUrl("Default", actionName, controllerName, new RouteValueDictionary(new { id = id }), RouteTable.Routes, Request.RequestContext, false);
return targetUrl;
}
And in client side
var id = 1;
$.get('/Home/GenerateActionLink?logicstatusId=5&id=' + id,function(res) {
var htmlMarkup = 'Blip';
// do something with htmlMarkup
// Ex : $('#SomeDivId').append(htmlMarkup);
});
But if you want to do this for many items, you might not want to make a call for each items, In that case,I would generate the base links and conditionally append the querystring values in javascript
var baseUrlBasic = "#Url.Action("Basic","HighBasic");
// Now later
var id = 1;
var newUrl = baseUrl+'?logicstatusId=5&id='+id;
// Use this to build the anchor tag
I am able to store the session variable in aspx page using the following way :
$(document).ready(function () {
var userName = "webruster";
'<%Session["UserName"] = "' + userName + '"; %>';
alert('<%=Session["UserName"]%>');
});
now when i am trying to retrieve the Session["UserName"] i am unable to get that value in cs . For this i have a work around but want to know the reason why it is failing ?
Alternative way :
Declaring hidden Variable and Link button
$(document).ready(function () {
var userName = "webruster";
'<%Session["UserName"] = "' + userName + '"; %>';
var x = document.getElementById("<%=hdnsessionvalue.ClientID %>");
x.value = '<%=Session["UserName"] %>';
document.getElementById('<%= lnkButton1.ClientID %>').click();
});
So i am able to retrieve the value in onclick event in server side.
My question :
So why i am unable to retrieve the session value in cs using the first method (i.e without assigning to hidden variable)
If you mean 'client side java script' then you can't, at least not directly. The session data is stored on the server and client side doesn't see it without communicating with server.
To access it can make an HTTP request and have server side modify or return the data.
Updated
Example
<script>
// get the variable
var data = JSON.Stringify(yourVariable);
// Make the ajax call
$.ajax({
type: "POST",
url: "aspPage.aspx/Method", //method we will call
contentType: "application/json; charset=utf-8",
data: {value: data }, //assign the 'data' values to 'value', its the data you want to send
dataType: "json",
success: function (result) {
alert('its working');
},
error: function (result) {
alert('something wrong');
}
});
</script>
on aspPage.aspx
[WebMethod]
public static void Method(string value)
{
sting val = value; // Do whatever you want to
}
You can not set or use Session from javascript directly as it is a Server Side State Management Technique. You should use Hidden Field for that purpose.
Set javascript variable to Hidden Field and in code behind, get the Hidden Field value and set it to your desired Session.
You can achieve it by:
Java Script
$(document).ready(function () {
var userName = "webruster";
var x = document.getElementById("<%=hdnsessionvalue.ClientID %>");
x.value = userName;
document.getElementById('<%= lnkButton1.ClientID %>').click();
});
Code Behind (CS)
protected void lnkButton1_Click(object sender, EventArgs e)
{
string test = hdnsessionvalue.Value;
Session["UserName"] = test ;
}