Sebastian
Sebastian

Reputation: 4811

Change Actionlink parameter from Javascript

I have a textbox to select Date and there is one action link in the razor page to redirect to another page with date value as one of the parameter. Is there any way to dynamically change the value of actionlink whenever a user change the date. My Razor view is like

<div class="col-md-4">
    @Html.TextBoxFor(model => model.Date, new { @class = "datepicker form-control" })
    @Html.ValidationMessageFor(model => model.Date)
</div>
@Html.ActionLink("Mark Attendance", "Add", "Attendance", new { @id = @model.ClassId }, new { @class = " btn btn-primary"})

And in Javascript i have been able to do

$("#Date").datepicker({
  showOn: 'both',
  altFormat: 'MM-dd-yy',
  dateFormat: 'MM-dd-yy',
  changeMonth: true,
  changeYear: true,
  yearRange: "1900:2050"
})
  .change(dateChanged)
  .on('changeDate', dateChanged);

function dateChanged(ev) {
  //How can i change the action link in a way that add an extra param date with selected value ?
}

Is there any way to do it?

Upvotes: 4

Views: 7113

Answers (2)

user3559349
user3559349

Reputation:

You can update the links href attribute using

var url = $('#mylink').attr('href'); // returns "Attendance/Add/1"
function dateChanged(ev) {
  $('#mylink').attr('href', url + '?date=' + <mydatevalue>);
}

note this assumes you give the link an id

@Html.ActionLink("Mark Attendance", "Add", "Attendance", new { id = @Model.ClassId }, new { @class = " btn btn-primary", new id = "mylink" })

which would redirect to

public ActionResult Add(int ID, DateTime date)

Upvotes: 3

Deepak Patel
Deepak Patel

Reputation: 474

You can change the value of date using javascript

$('.btn btn-primary').attr('href', function () {
        return this.href.replace('_Parameter1', Date_Value);
          });

In View:-

@Html.ActionLink("Mark Attendance", "Add", "Attendance", new { @id = @model.ClassId,Parameter1='_Parameter1'}, new { @class = " btn btn-primary"})

In Controller:-

public ActionResult Add(int ID, DateTime date)

Upvotes: 4

Related Questions