Reputation: 2143
Strait to the details...
I'm working on a personal project basically it's a task list. Anyways; I managed to get the standard Add, Edit, Delete a task functionality going good; now I'm stuck on something that I know must be very simple. I would like for users to be able to accept a task from the details page, now I could easily put that option in a drop down list and allow the user to select it and then save; BUT i would like to just provide a link that they can click "Accept Task" that link then goes to my controller action and pulls the task then updates the TaskStatus field.
This is my controller action
//
// TaskStatus Updates
[AcceptVerbs(HttpVerbs.Post), Authorize]
public ActionResult AcceptTask(int id)
{
Task task = taskRepository.GetTask(id);
try
{
task.TaskStatus = "Accepted";
taskRepository.Save();
return RedirectToAction("Details", new { id = task.TaskId });
}
catch (Exception)
{
throw;
}
}
So now how do I call this action from within my "Details" view?
Upvotes: 2
Views: 13217
Reputation: 15901
A link should not perform any action by definition. It leads to strange problems: What happens when google crawls your site? What happens when somebody refreshes the page? What happens when somebody bookmarks the page?
Actions that change content are usuallly done by get after post. First post to the Action that changes something (AcceptTask) then redirect to a page that displays the result. In you case I would suggest for the get the list of tasks with a success message. For the Mesage to be available after redirect use Tempdata.
Upvotes: 1
Reputation: 122644
A link (<a>
) cannot post a form, so you have three choices:
<input type="image">
instead, which you can finesse to look similar to a link;There's already an answer posted for #1, which is easily modified to #2. I'll post a jQuery example for #3, although you can use any JS library for this:
<a id="acceptTaskLink" href="#">Accept</a>
<span id="accepted" style="display: none">Accepted</span>
...
<script type="text/javascript">
$('#acceptTaskLink').click(function() {
$.post('/site/task/accept',
function(result) {
$('#acceptTaskLink').hide();
$('#accepted').show();
});
});
</script>
This script makes an Ajax post to the controller, then after it successfully posts, it changes the "Accept" link into regular "Accepted" text (by hiding the link and showing a confirmation element, which is presumably in the same place).
Upvotes: 1
Reputation: 532465
A small form containing a button that posts back to the AcceptTask action would work. It could even be an AJAX form, if you wanted.
<% using (Html.BeginForm("accepttask","task",new { id = Model.TaskId })) { %>
<input type="submit" value="Accept Task" />
<% } %>
Upvotes: 2