DropDown list onchange event and AJAX in MVC - asp.net-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();”

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();" })

How to pass an actionlink's results to a partialview placeholder?

Okay, so in my page I have a list of links:
#foreach (var item in Model)
{
#Html.ActionLink(item.Name, "Recruitments", new { Id = item.Id })
<br />
}
And what I want is for the partialview to return somewhere else on the page, in a placeholder I've set aside.
Is this possible? Or do I have to use jquery ajax calls instead somewhere?
you can #Ajax.ActionLink in asp.net mvc, it has different overloads you can use according to your requirements here is the code:
#Ajax.ActionLink("ActionName", // action name
"Recruitments", //controller name
new { Id = item.Id }, // route values
new AjaxOptions { HttpMethod = "GET", //HttpMethod Get or Post
InsertionMode = InsertionMode.Replace, // Replace content of container
UpdateTargetId = "Container", // id of element in which partial view will load
OnComplete = "Completed();" }) // js function to be executed when ajax call complete
<div id="Container">
</div>
<script>
function Completed()
{
alert("completed");
}
</script>
I did had a problem with partial for your problem post some code so I understand your problem.
Either you should use a razor helper, either you simply use jquery to manipulate the dom.
note that jquery is pretty simple
$("#selectorOnYourPlaceHolder").html($("#selectorOnYourLinks").html());
$("#selectorOnYourLinks").html("")
You want to do this with Ajax:
$.ajax({
type: "GET", url: "somePageOrHandler.aspx", data: "var1=4343&var2=hello",
success: function(data)
{
$('#someDivInPlaceHolder').html( data);
}
});

How to Pass textbox value using #html.actionlink in asp.net mvc 3

How to Pass value from text using #html.actionlink in asp.net mvc3 ?
None of the answers here really work. The accepted answer doesn't refresh the page as a normal action link would; the rest simply don't work at all or want you to abandon your question as stated and quit using ActionLink.
MVC3/4
You can use the htmlAttributes of the ActionLink method to do what you want:
Html.ActionLink("My Link Title", "MyAction", "MyController", null, new { onclick = "this.href += '&myRouteValueName=' + document.getElementById('myHtmlInputElementId').value;" })
MVC5
The following error has been reported, but I have not verified it:
A potentially dangerous Request.Path value was detected
Rather than passing your value using #Html.actionlink, try jquery to pass your textbox value to the controller as:
$(function () {
$('form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: { search: $('#textboxid').val()},
success: function (result) {
$('#mydiv').html(result);
}
});
return false;
});
});
This code will post your textbox value to the controller and returns the output result which will be loaded in the div "mydiv".
to pass data from the client to the server you could use a html form:
#using (Html.BeginForm(actionName,controllerName)) {
<input type="text" name="myText"/>
<input type="submit" value="Check your value!">
}
be sure to catch your myText variable inside your controller's method
you can use this code (YourValue = TextBox.Text)
Html.ActionLink("Test", new { controller = "YourController", action = "YourAction", new { id = YourValue }, null );
public class YourController : Controller
{
public ActionResult YourAction(int id)
{
return View("here your value", id);
}
}

Ajax.Actionlink, partial and webgrid issue

I have the following issue.
My url structure is like this:
/people/edit/usercode
In my controller i have the following:
[AcceptVerbs(HttpVerbs.Post)]
public PartialViewResult LoanRefresh(string id)
{
PeopleModel p = new PeopleModel();
return PartialView("_LoanHistory", p.getPersonLoanHistory(id));
}
In my view i have:
#Ajax.ActionLink("Refresh", "LoanRefresh", new { id = Model.IdentityCode }, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "loanHistory", LoadingElementId = "Loading" }, new { #class = "button" })
and
<div id="loanHistory">
#Html.Partial("_LoanHistory", Model.Loans)
</div>
When run the Ajax.ActionLink it gets the data back ok and it updates the div, but the url of the sort links on the webgrid then change their address to:
/People/LoanRefresh/AFU0006?sort=CreatedOn&sortdir=ASC
i need to stay as:
/People/Edit/AFU0006?sort=CreatedOn&sortdir=ASC
Any help would be greatly appreciated.
Well #Nick, that's because your action name is LoanRefresh and not Refresh. To do that you will probably have to do some routing or even redirect your LoanRefresh results to an action named Refresh.
Try setting ajaxUpdateContainerId to an object that is specified in the partial view, rather than an object in the view from which the partial view is originally called. The sort URLs should work correctly then.

Resources