ASP Route Data attribute in HTML Actionlink - asp.net-mvc

I have a href attribute using anchor tag helper asp-all-route-data. I want to change this to use HTML.ActionLink that has a onclick popup message but not sure how to do it.
I have tried this so far:
#Html.ActionLink("Set as Draft", "SetAsDraft", "Item", new {
FromRouteAttribute = "setAsDraftParams" },
new { onclick = "return
confirm('Are sure you want to set this Item as a draft?');" })
Current a href:
<a asp-area="Admin" title="Set as Draft DOR" asp-controller="Dor" asp-
action="SetAsDraft" asp-all-route-data="setAsDraftParams">Set as Draft
DOR</a>
Variable set in the View:
var setAsDraftParams = new Dictionary<string, string>
{
{ "id", Model.DraftToView.ItemId.ToString() },
{ "returnViewName",
nameof(Web.Areas.Admin.Controllers.ItemController.Index)
}
};
I expect the HTML.ActionLink to return to the viewname set in the setASDraftParams variable

Since you are using dictionary, you need to use the right key to get the value. DictionaryVariable[key]
Try with:
#Html.ActionLink("AQUI", "Index", "Home", new { FromRouteAttribute = setAsDraftParams["returnViewName"] },
new { onclick = "return confirm('Are sure you want to set this Item as a draft?');" })

Related

MVC URL routing to target specific urls [duplicate]

I'm creating a form for a DropDown like this:
#{
Html.BeginForm("View", "Stations", FormMethod.Get);
}
#Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"), new { onchange = "this.form.submit();" })
#{
Html.EndForm();
}
If I choose a value from my dropdown I get redirected to the correct controller but the URL is not as I would like to have it:
/Stations/View?id=f2cecc62-7c8c-498d-b6b6-60d48a862c1c
What I want is:
/Stations/View/f2cecc62-7c8c-498d-b6b6-60d48a862c1c
So how do I get the id= querystring parameter replaced by the more simple URL Scheme I want?
A form with FormMethod.Get will always post back the values of its form controls as query string values. A browser cannot generate a url based on your route configurations because they are server side code.
If you really wanted to generate /Stations/View/f2cecc62-7c8c-498d-b6b6-60d48a862c1c, then you could use javascript/jquery to build your own url and redirect
#using (Html.BeginForm("View", "Stations", FormMethod.Get))
{
#Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"))
}
var baseUrl = '#Url.Action("View", "Stations")';
$('#id').change(function() {
location.href = baseUrl + '/' $(this).val();
});
Side note: Submitting on the .change() event is not expected behavior and is confusing to a user. Recommend you add a button to let the user make their selection, check it and then submit the form (handle the button's .click() event rather that the dropdownlist's .change() event)
Remove "id"
from
#Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"), new { onchange = "this.form.submit();" })

Passing route values from a form using FormMethod.Get [duplicate]

I'm creating a form for a DropDown like this:
#{
Html.BeginForm("View", "Stations", FormMethod.Get);
}
#Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"), new { onchange = "this.form.submit();" })
#{
Html.EndForm();
}
If I choose a value from my dropdown I get redirected to the correct controller but the URL is not as I would like to have it:
/Stations/View?id=f2cecc62-7c8c-498d-b6b6-60d48a862c1c
What I want is:
/Stations/View/f2cecc62-7c8c-498d-b6b6-60d48a862c1c
So how do I get the id= querystring parameter replaced by the more simple URL Scheme I want?
A form with FormMethod.Get will always post back the values of its form controls as query string values. A browser cannot generate a url based on your route configurations because they are server side code.
If you really wanted to generate /Stations/View/f2cecc62-7c8c-498d-b6b6-60d48a862c1c, then you could use javascript/jquery to build your own url and redirect
#using (Html.BeginForm("View", "Stations", FormMethod.Get))
{
#Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"))
}
var baseUrl = '#Url.Action("View", "Stations")';
$('#id').change(function() {
location.href = baseUrl + '/' $(this).val();
});
Side note: Submitting on the .change() event is not expected behavior and is confusing to a user. Recommend you add a button to let the user make their selection, check it and then submit the form (handle the button's .click() event rather that the dropdownlist's .change() event)
Remove "id"
from
#Html.DropDownList("id", new SelectList(ViewBag.Stations, "Id", "Name"), new { onchange = "this.form.submit();" })

Remove / Delete a dynamically created partial view mvc

I am trying to add a remove/delete a dynamically created partial view.
This is my ADD script.
$("#btnAdd").on('click', function () {
$.ajax({
async: false,
url: '/Employees/Add'
}).success(function (partialView) {
$('#AddSchedule').append("<tbody>" + partialView + "</tbody>");
});
});
this is the add controller
public ActionResult Add()
{
var schedViewModel = new FacultySchedViewModel();
return PartialView("~/Views/Employees/_DynamicView.cshtml", schedViewModel);
}
this is the partial view _DynamicView.cshtml
#using(Html.BeginCollectionItem("New")){
<td>
#Html.ActionLink("Delete", "DeleteThis", "MyController", null)
</td>
<td>
#Html.EditorFor(model => #Model.Schedule, new { htmlAttributes = new { #class = "form-control" } })
</td> }
what i can't figure out are
how to get the ID generated by BeginItemCollection
use the ID in a remove script
action on the controller
EDIT
1. How to connect it to a button or a link for removing the row
Added the view on the the Main of the partial view
#for (int i = 0; i < #Model.New.Count(); i++)
{
#Html.EditorFor(model => #Model.New[i])
}
The BeginItemCollection add a Guid as an indexer to the controls name and id attributes. It has no relevance at all to identifying an item to delete. You need add include the value of the property that identifies the FacultySchedViewModel object. Assuming its int ID, then change the partial to include a button and add the ID as a data- attribute
#using(Html.BeginCollectionItem("New"))
{
<tr>
<td><button type="button" class="delete" data-id="#Model.ID">Delete</button></td>
<td>#Html.EditorFor(model => #Model.Schedule, new { htmlAttributes = new { #class = "form-control" } })</td>
</tr>
}
Then your script would be
var url = '#Url.Action("Delete")'; // assumes its in the same controller
$('.delete').click(function() {
var id = $(this).data('id');
var row = $(this).closest('tr');
if (id) { // or if(id == 0) depending if your property is nullable
row.remove(); // the item never existed so no need to call the server
return;
}
$.post(url, { ID: id }, function(response) {
if(response) {
row.remove(); // OK, so remove the row
} else {
// Oops - display and error message?
}
});
});
and the controller
[HttpPost]
public JsonResult Delete(int ID)
{
// Delete the item in the database
return Json(true); // or if there is an error, return Json(null); to indicate failure
}
Side note:
$('#AddSchedule').append("<tbody>" + partialView + "</tbody>"); is
adding a new tbody element for each item. Instead the main view
should include the tbody element and give it the id so its
$('#AddSchedule').append(partialView); or use $('#AddSchedule
tbody')append(partialView);
Does the model your posting back really have a property named New
(as you indicate in the BeginItemCollection method)?
As per your html render, what I suggest to modify your partial view as
From
#Html.ActionLink("Delete", "DeleteThis", "MyController", null)
To
#Html.ActionLink("Delete", "DeleteThis", "MyController", new { hidefocus = "hidefocus" } ) //add custom properties for here, which you can grab at client side or give css here.
Now search the anchor link via jQuery: Find the element with a particular custom attribute
When you get id, you can go parent like $('#id').parent().parent().hide() or empty()
or
As second option, is on click of Delete button call the same controller , but with a parameter to identify delete, so while returning give the null will bind in ajax again with empty string.
Why does Html.ActionLink render "?Length=4"
http://forums.asp.net/t/1787278.aspx?Add+and+remove+partial+views

DropDown list onchange event and AJAX in MVC

I have a code block in my MVC view as follows:
<%using (Ajax.BeginForm("MyAction", new { action = "MyAction", controller = "Home", id = ViewData["selected"].ToString() }, new AjaxOptions { UpdateTargetId = "Div1" }))
{ %>
<%=Html.DropDownList("ddl", ViewData["MyList"] as SelectList, new { onchange = "this.form.submit()" })%>
<%} %>
I want to set the value of ViewData["selected"] so that i can send it to the desired action.
Can anyone please suggest how can i do this?
thanks!
Instead of using a form, why not use a jQuery onChange event on your drop down?
$(document).ready(function() {
$("#ddl").change(function() {
var strSelected = "";
$("#ddl option:selected").each(function() {
strSelected += $(this)[0].value;
});
var url = "/Home/MyAction/" + strSelected;
$.post(url, function(data) {
// do something if necessary
});
});
});
ViewData is not the place to pass data back to the server side. Values of html input controls within form tag are conveniently available in action method. You can get these values either from various types of action method arguments (model, formcollection etc).
Here is a link to free asp.net mvc ebook tutorial. Is a good resource for asp.net mvc.
Found solution at this post it is just small chnge
Yes, that’s right – only change is replacing:
onchange = “this.form.submit();”
with:
onchange = “$(this.form).submit();”

Read htmlAttribute in controller

I have Ajax.ActionLink with htmlAttribute param
<%= Ajax.ActionLink("cool", "ViewCategory", new { id = elem.ID }, new AjaxOptions { UpdateTargetId = "score_" + elem.ID.ToString() }, new { myAttr = 123 } )%>
How can I read this attribute in controller method?
You can't.
All the htmlAttribute param does is instruct the generation of additional attributes to be added to the anchor html with it is sent to the client. These attributes are not included in the request when the anchor is clicked.
Place the attribute along side the id new {id = elem.ID, UpdateTargetID = ...} this should be included in the URL.

Resources