Dropdownlist box in asp.mvc 2 and jquery [duplicate] - c#

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 Html.BeginForm different URL schema

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

Hook javascript to dropdownlist change

¡Hola!
My current task is to have a page where, with a dropdownlist, a user can select a deck title. Once a title is selected, the page should postback with details on that deck.
Here's what I've got at the moment:
#model IEnumerable<SCATChartsMVC.Models.Charts_DeckList>
#{
ViewBag.Title = "Index";
if (IsPost) { ViewBag.Title = "We posted back!"; }
}
<h2>Index</h2>
#{ var list = ViewData.Model.Select(cl => new SelectListItem
{
Value = cl.RecNum.ToString(),
Text = cl.DeckTitle.ToString()
});
}
#using (Html.BeginForm("Details", "Charts_DeckList", FormMethod.Post))
{
#Html.DropDownList("deckTitles", list, "---------select---------")
<input type="submit" name="submit" value="Submit" />
#Html.ActionLink("Details", "Details", "Charts_DeckList", new { id = list.ElementAt(4).Text }, "")
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
$("deckTitles").change(function () {
if ($("#deckTitles").val() != "") {
var test = {};
test.url = "/Charts_DeckList/Details";
test.type = "POST";
test.data = JSON.stringify($('#deckTitles').val());
test.datatype = "json";
test.contentType = "application/json";
test.success = true;
test.error = function () { alert("Error!"); };
$.ajax(test);
}
})
</script>
The input tag and ActionLink under Html.BeginForm were for my own testing purposes; the ActionLink works correctly if I specify the element. I'm hoping to be able to pass something similar back whenever a user clicks a selection, as opposed to whenever they hit the "details" button.
The submit input tag does not work. It does route properly to Charts_DeckList/Details, but the parameter in the action is always null.
I'm just getting into the whole MVC/Web rigamarole, so there's a lot I don't know that I'm not even aware I don't know. While I've seen a number of different resources on the internet suggesting different things, much of the web development jargon is lost on me at this point in time, and much of the way these things work under the hood is lost on me since VS seems to put together so much of it automagically.
Any pointers would be appreciated. Thank you.
barrick's suggestion below is correct!
I also had to move the script tags up into the BeginForm brackets, heads up.
You're not setting the ID of the DropDownList there, the first argument sets the name attribute of the dropdown (used to identify the value in the POST variable collection on server postback) - you'll need to add another argument to set the ID:
#Html.DropDownList("deckTitles", list, "---------select---------", new { #id = "deckTitles" });
You can then pick up the selected value in the jQuery as follows:
$("#deckTitles option:selected").val();

JQuery function attached to Ajax ActionLink

Quick question.
I have a Ajax.Action link intended to upload the next section of a form asynchronously.
#Ajax.ActionLink("Next" , "matches",null, new AjaxOptions {UpdateTargetId = "placeholder", InsertionMode = InsertionMode.InsertAfter,HttpMethod = "GET"}, new { #class = "button" })
I've applied my "button" class to it, which gives it the appearance of a big button.
I'm looking to attach a JQuery .click event to the above AjaxAction link triggering a function that will hide the previous form. I'm using the JQuery below to do so:
<script>
$(document).ready(function () {
$(this).closest("a.button").click(function () {
$("form.common").hide();
});
});
</script>
This is not working for me. The Ajax.ActionLink works fine, just not the Jquery. Below is rough breakdown of my page.
<form class="common"> (this form needs to hide)
//lots of inputs
<ActionLink class="button>
</form>
<div id="placeholder">
(this is where the new form will be inserted)
</div>
I'm new to C# and JavaScript/JQuery, so I'm hoping someone can point me in the right direction here.
Rather than using any special events with jQuery, you could call a JS method in the beginning of ajax request performed by ajax link.
Add OnBegin property in your link AjaxOptions and assign a JS function into it and do the logic in that JS function
Ajax Link
new AjaxOptions { OnBegin = "OnBegin" ... }
JS
function OnBegin() {
$("form.common").hide();
}
Hope this will help !!
Try to target your element directly instead of using closest. If you can also use the buttons id or assign a more descriptive class.
$("a.action_button").click(function () {
$("form.common").hide();
});

How to pass dynamic values using MVC AJax.BeginForm

I'm using MVC and AJax.BeginForm to do some ajax updating of my page. The BeginForm code looks something like:
using (Ajax.BeginForm("HandleCrop", "Card",
new
{
accept = true,
id = Model.ImageUpload.ID,
file = Model.ImageUpload.File,
imageCropX = Model.CropInfo.X,
imageCropY = Model.CropInfo.Y,
imageCropWidth = Model.CropInfo.Width,
imageCropHeight = Model.CropInfo.Height
},
new AjaxOptions
{
HttpMethod = "POST",
OnComplete = "ConfirmCompleted",
OnSuccess = "ReloadUpload",
OnFailure = "Failure"
}, null))
The Model.CropInfo is being put in as hidden fields like so:
<%=Html.HiddenFor(m => m.CropInfo.X) %>
<%=Html.HiddenFor(m => m.CropInfo.Y) %>
<%=Html.HiddenFor(m => m.CropInfo.Width) %>
<%=Html.HiddenFor(m => m.CropInfo.Height) %>
However, these values are being dynamically modified by some client side javascript, and these values need to be posted through the Ajax call back to the server. The above code will obviously not work as the imageCrop.. parameters in the Ajax form are being filled when the page is rendered (therefore being all 0).
My question is: what is the correct way to approach this situation?
From Ajax this part should be absolutely removed:
imageCropX = Model.CropInfo.X,
imageCropY = Model.CropInfo.Y,
imageCropWidth = Model.CropInfo.Width,
imageCropHeight = Model.CropInfo.Height
With TryUpdateModel in the Action your CropInfo should be filled OK from posted data.
If you are NOT USING automatic update of the model (or via TryUpdateModel)
and instead of that you are USING this data as input parameters in Action then just rename these Action parameters to CropInfo_X, CropInfo_Y, CropInfo_Width and CropInfo_Height (I think this is how the hidden fields will be named in HTML, check this in page source)

How to make a link in a Telerik MVC grid template column send a post to an action

There is a lot going on here.
I have a Telerik MVC grid with the following templated column:
#(Html.Telerik().Grid((IEnumerable<User)Model.Data)
.Name("UsersGrid")
.DataKeys(keys => keys.Add(c => c.UserName))
.DataBinding(dataBinding => dataBinding.Server()
.Columns(c =>
{
c.Bound(r => r.FullName).Title("");
c.Bound(r => r.UserName).Title("");
c.Template(
#<text>
#if(#item.Status == "Pending")
{
#Html.ActionLink("Resend Invite", "ResendInvite", new { Email = #item.UserName, FirstName = #item.FullName }, new { #class = "reesendInviteLink" })
}
</text>
).Title("Link").HtmlAttributes(new { Style = "text-align: right;" });
}));
Now I know ActionLink will not call a post action so I'm doing the following with jquery:
$(document).ready(function () {
$(".resendInviteLink").click(function (e) {
var url = e.currentTarget.href;
$.post(url);
});
});
The Action method I am trying to call looks like this:
[HttpPost]
public ActionResult ResendInvite(UserVM user)
{
//....Do Something
}
When I debug the jquery everything goes well until I reach the $.post and then it fails saying that it cannot find the ResendInvite action on the controller. In a way I think it makes sense since the ActionLink is looking for a Get, not a Post.
So how can I create a link on the grid that will:
1. Get the email and the user's name from the Telerik grid.
2. Call a post action method with the correct paameters.
Thanks for your help.
Your problem is that although you've subsribed on the link's click event with Jquery, the link's original click event still fires a Get request which fails.
You need to use the preventDefault method
$(".resendInviteLink").click(function(e) {
e.preventDefault();
var url = e.currentTarget.href;
$.post(url);
});
Or return false form the event handler:
$(".resendInviteLink").click(function(e) {
var url = e.currentTarget.href;
$.post(url);
return false;
});

Categories

Resources