Asp.net MVC - call database on dropdown value change - asp.net-mvc

I am new to MVC. i want call database on dropdown value change. Does anybody know how to do that.
Regards,
vangli

MVC does not have a post-back mechanism as such as you had in WebForm (well, this was being carried out as javascript posting the form.
What you can do is create some javascript using jquery if you want to trigger some action when the item in that dropdown changes. it would be, (assuming the id of the dropdown is idDropDown
$('#idDropDown').change(function () {
$.ajax(#Url.Action("AjaxAction", "MyController")', { selection : selectedValue }, function (data)){
//handle ajax response here
};
});
Your action controller will be like this:
public ActionResult AjaxAction(string selection)
{
// do your server-side processing and get your data
return Json(data);
}

With out jquery you can POST the data to controller action using pure java script.
#Html.DropDownListFor(m => m.SelectedValue,Model.SelectListItems,new{ onchange = "this.form.submit();" })
Note: Here simply you can submit form by adding java script code to on change. This is similar that you click on submit button.

Related

How to execute Action method on click through scripts

In my app I have a button. By clicking this button I want to execute an action method.
This action method does not have any view.
My requirement is: "call this action method in on click event"
How can I execute the the method on the click event?
my Onclick event is
$('#Delete').click(function () {
#* #(Url.Action("Delete", new { id="cera123"}))*#
$.ajax({
url: '#(Url.Action("Delete", new { id="cera123"}))',
type: "GET",
success:function () {
alert('deleted');
}
});
my action method is
public ActionResult Delete(string id)
{
obj.EmpLi.RemoveAll(x => x.EmployeeId == id);
return RedirectToAction("Index", obj);
}
delete action is performed but i an see the result after voluntarily refreshing the page even though i gave RedirectToAction("Index")
thanks
$(function(){
$("#yourbutonId").click(function(){
$.get("/controller/action/id",function(data){
//data is what your action return
});
});
});
nilesh is right $.ajax is js,and $.get is sample use base on $.ajax
or $.post
to make these code work,you should ref jquery.js
Some background info...
If you come from the webforms and code-behind world is common to you that an HTML element calls a script in the code, but actually what asp.net webforms does is an http call to the script on the server. If you had an updatepanel, asp.net webforms would have done the same call via ajax.
That's the reason why in asp.net webforms the elements have the preceding asp: on their branded html tags. That way asp.net can convert their branded elements to real HTML elements.
The answer
The only way to execute the code of an action from an HTML element on-click event in asp.net MVC is by calling the URL that gets to that method. Either via ajax or by a request from the browser, an http request needs to be done.
With javascript you can listen when an element's on-click event is fired and then do some logic. If you're using jquery you can use the $.ajax() or $.get() methods to make a call to your action URL.

ChildAction triggered on dropdown change in partial view

I want to trigger a ChildAction on the Home Controller on the onchange event of a dropdown. The dropdown is located at the _Layout.cshtml.
Is it possible to do it on javascript?
Here is my code as of the moment.
$('#langDropdown').change(function() {
var lang = $(this).val();
alert(lang);
});
And here is my dropdown:
#Html.DropDownList("Language", ViewData["Languages"] as SelectList,
new { id = language })
It not inside of any form. Any suggestion how can I do it. Thanks!
Note: I just use alert for testing purposes.
You should put your dropdown in a form that submits a POST request to a separate action (this action can have the same name as the child action).
The POST action would want to redirect back to the original URL, as I explained in my previous answer (see also comments).

In MVC3 how do I have a dropdown that shows/hides fields based on the selected value?

I have a dropdown of countries, and an address form. Depending on the country selected, I want to hide/show certain fields. I'm quite new to MVC and MVC3, what is the best way to do this?
I have on the page a 'DropDownListFor' that populates correctly. When this changes, I imagine I need to ask the server which fields to show/hide. I could perhaps put some JQuery into a change event that calls a method, and it returns some json saying visible:true for each field, but I don't know if that's ideal or even how to implement it (possibly $.ajax or something).
Any ideas?
Edit: I should add the hard part of this is asking the server what fields to show for each country as there are many countries and the possibilities are all stored in the database. I am accustomed to webforms not MVC so I would ordinarily postback and have serverside logic, but this isn't an option with MVC afaik...
I have deleted my first answer as it was irrelevant.
With MVC3 you can send an AJAX request to any method.
In HomeController.cs:
public List<string> GetFieldsToShow(string id)
{
// if you routing is left to default, the parameter passed in will be called 'id'
// Do what you gotta do...
List<string> listOfFieldsToShowBasedOnCountry = GetList(id);
return listOfFieldsToShowBasedOnCountry;
}
And in the AJAX call, something like...
$.ajax({
type: 'POST',
url: '/Home/GetFieldsToShow/' + valueOfSelectedDropDownItem,
/*etc...*/
success: function(data){
$(data).each(function(){
$('#' + this).show();
}
}
});

ASP MVC + AJAX, trying to Update a div asynchronously

I'm new to Asp MVC, and I'm trying to accomplish a little async update (I'm using MVC3 RC2, with Razor, but I can manage with ASPX solutions too).
I have a Master page, which renders a shopping cart box on every page by calling Html.RenderAction("Cart","Shop"). The Cart action of the ShopController calls the database, etc, and outputs the results. This works.
First problem: if I put an ActionLink in this partial view (like Html.ActionLink("Remove")), then even if I call PartialView() from the Remove action, it renders only the shopping cart, and nothing else (in essence, my page disappears).
Second problem: There is a div called "cartContent" inside this partial view. I want to be able to put a link ANYWHERE (not just on the Master page or in the partial view), which when pressed calls a controller Action, and then updates ONLY the cartContent div based on the results. I've tried Ajax.ActionLink but it does the same as Html.ActionLink, even though I imported the Microsoft.MvcAjax js libs.
Also, if I solve the first problem, I want that to be async as well.
What solution do I use? I've tried setting UpdateTargetID to "cartContent", I've tried wrapping the cartContent into an Ajax.BeginForm, nothing. Do I HAVE to use jQuery (which I know nothing of)? Do I serialize some response to JSON, and update the div manually in Javascript? (I'm not really good at JS, I'm coming from the C# side of things)
You put a link wherever you want:
#Html.ActionLink("remove item", "remove", "somecontroller",
new { id = Model.Id }, new { #class = "remove" })
And then in a separate javascript file:
$(function() {
$('.remove').click(function() {
// when the link is clicked
// perform an ajax request:
$.ajax({
url: this.href,
type: 'delete',
success: function(result) {
// when the AJAX call succeed do something with the result
// for example if the controller action returned a partial
// then you could show this partial in some div
$('#someDivId').html(result);
}
});
// don't forget to cancel the default action by returning false
return false;
});
});
Remark: if the div you are updating contains also the link then you might need to use the .live() function or the click event handler will not work the second time because the DOM will be modified:
$('.remove').live('click', function() {
...
});

autopostback for dropdownlist in mvc.net

how to set autopostback for dropdownlist in mvc.net?
You don't - there's no concept of 'autopostback', in the same way that there is no postback concept in the MVC framework.
If you want to submit the form, you can do that via javascript, if you want to update something else via a call to the server, you can set up an AJAX call, probably using jQuery to do so.
There's a bit of an example here.
no jquery required. wrap each hidden id and dropdown in a form with the action to updateproduct. then its just:
#Html.DropDownList("id", (SelectList)ViewBag.Values, new { onchange = "this.form.submit();" })
autopostback supports only in asp.net not in mvc.net, so you just need to write #Html.DropDownList("id", (SelectList)ViewBag.Values, new { onchange = "this.form.submit();" }) or jquery function in the cshtml file script section.
One thumb rule for MVC,
Any method of controller, on
be called by JS or Jquery thru Ajax calling routing.

Resources