You're asking several things:
- How to handle a click event in JavaScript
- How to get a data-* value in JavaScript
- How to redirect in JavaScript
- How to include a value on a URL
- How to receive a value in an action method
Let's start with the first one, a click event. Since you're getting started with ASP.NET MVC, I'm going to assume jQuery is included in the project template. So a click event might look something like this:
$('div.card').on('click', function () {
});
This would invoke that (currently empty) function any time a user clicks on a <div>
with class="card"
. In that function you want to grab the value of the data-* attribute of the <div>
which was clicked:
$('div.card').on('click', function () {
let csid = $(this).data('csid');
});
Now you want to redirect to a URL and include that value. There are a variety of ways to build a URL in ASP.NET MVC and some have interesting workarounds when used in JavaScript. But let's keep it simple. Use the Url.Action
helper, and remember to wrap it in quotes in JavaScript since it's a string:
$('div.card').on('click', function () {
let csid = $(this).data('csid');
let url = '@Url.Action("Customer", "Customer")';
});
(You are encouraged to look at the page source in your browser to see what this generated.) And you can add the value to the query string of the URL this generates:
$('div.card').on('click', function () {
let csid = $(this).data('csid');
let url = '@Url.Action("Customer", "Customer")' + '?csid=' + csid;
});
Then use that URL to redirect the user:
$('div.card').on('click', function () {
let csid = $(this).data('csid');
let url = '@Url.Action("Customer", "Customer")' + '?csid=' + csid;
window.location.href = url;
});
Important Note: The difference may seem unimportant, but understanding the semantics of what's going on is very important. You are not redirecting the user to Customer.cshtml
. You are redirecting the user to the action method on the controller. When that action method returns a view, that view will be Customer.cshtml
.
This becomes important when you want to use the value that's on the query string. Since the user is going to the action method, get that value in the action method:
public ActionResult Customer(string csid)
{
return View();
}
Now obviously the question becomes... What do you plan to do with that csid
value. This is pretty much where the context of your question ends. At this point you've redirected the user with the value, how you use that value is up to you. If you want to pass it from the controller action to the view then the standard approach would be to set the value on a model that you pass to your view. For example:
public ActionResult Customer(string csid)
{
var model = new SomeViewModel { CSID = csid };
return View(model);
}
Then in your view you would put this line at the top to bind to that model:
@model SomeViewModel
From there you can access Model.CSID
wherever you want in your view.