how to do postback on changing dropdownlist selected item in mvc4 - asp.net-mvc-4

I have a dropdown in my page. On selecting a value in dropdown I want the label text to be changed. Here is my code :
#model FND.Models.ViewLender
#{
ViewBag.Title = "Change Lender";
}
#using (Html.BeginForm())
{
#Html.Label("Change Lender : ")
#Html.DropDownList("Ddl_Lender", Model.ShowLenderTypes)
#Html.DisplayFor(model => model.Description)
}
On changing the value in dropdownlist I want the Description to change accordingly.

You could start by putting the description into a div and give your dropdown an unique id:
#model FND.Models.ViewLender
#{
ViewBag.Title = "Change Lender";
}
#using (Html.BeginForm())
{
#Html.Label("Change Lender : ")
#Html.DropDownList("Ddl_Lender", Model.ShowLenderTypes, new { id = "lenderType" })
<div id="description">
#Html.DisplayFor(model => model.Description)
</div>
}
Now all that's left is to subscribe to the onchange javascript event of this dropdown and update the corresponding description.
For example if you are using jQuery that's pretty trivial task:
$(function() {
$('#lenderType').change(function() {
var selectedDescription = $(this).find('option:selected').text();
$('#description').html(selectedDescription);
});
});
This being said I probably misunderstood your question and this description must come from the server. In this case you could use AJAX to query a controller action that will return the corresponding description. All we need to do is provide the url to this action as an HTML5 data-* attribute to the dropdown to avoid hardcoding it in our javascript file:
#Html.DropDownList(
"Ddl_Lender",
Model.ShowLenderTypes,
new {
id = "lenderType",
data_url = Url.Action("GetDescription", "SomeController")
}
)
and now in the .change event we trigger the AJAX request:
$(function() {
$('#lenderType').change(function() {
var selectedValue = $(this).val();
$.ajax({
url: $(this).data('url'),
type: 'GET',
cache: false,
data: { value: selectedValue },
success: function(result) {
$('#description').html(result.description);
}
});
});
});
and the last step of course is to have this controller action that will fetch the corresponding description based on the selected value:
public ActionResult GetDescription(string value)
{
// The value variable that will be passed here will represent
// the selected value of the dropdown list. So we must go ahead
// and retrieve the corresponding description here from wherever
// this information is stored (a database or something)
string description = GoGetTheDescription(value);
return Json(new { description = description }, JsonRequestBehavior.AllowGet);
}

Related

How do I get the Selected Value of a DropDownList in ASP.NET Core MVC App

I have the following dropdownlist in my view:
#{
var listado = new List<SelectListItem>()
{
new SelectListItem()
{
Text ="YES",
Value ="1"
},
new SelectListItem()
{
Text = "NO",
Value = "2"
}
};
}
<div class="form-group">
<label class="control-label">Is it True ?</label>
#Html.DropDownList("miDropDownList",listado)
</div>
I want to get the selected value 'YES' or 'NO' to do something in the controller like so:
IActionResult ControllerAction(){
var theValue = dropdownList.SelectedValue //this is pseudocode syntax but you understand I want to get
//the value
// with the value I will do something like this:
User userinstance = new User {
Id = 1,
Name = "john",
isJohnTall = theValue.Value
}
}
I want something simple in other answers I've seen DropDownLists that are bound to models, but I just want to get strings selected in the dropdown and be able to do something with them in the controller.
You can use JQuery with ajax.
Something like this:
<div class="form-group">
<label class="control-label">Is it True ?</label>
#Html.DropDownList("miDropDownList", listado, new { #onchange = "GetYesOrNo()"})
</div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
function GetYesOrNo() {
var selectElement = document.querySelector('#miDropDownList');
var option = selectElement.value;
$.ajax({
url: '/Home/GetYesOrNo',
type: 'GET',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
mimeType: 'text/html',
data: { getOption : option },
success: function (returnValue) {
alert(returnValue);
}
});
};
</script>
And in Home Controller, add this JsonResult:
public JsonResult GetYesOrNo(int getOption)
{
if (getOption == 1) return Json("Option: YES");
return Json("Option: NO");
}
You can use a form to submit your data.
The form will submit Value, so you can modify your value as Text.
You can change your code like below.
View:
#{
var listado = new List<SelectListItem>()
{
new SelectListItem()
{
Text ="YES",
Value ="YES"
},
new SelectListItem()
{
Text = "NO",
Value = "NO"
}
};
}
#using (Html.BeginForm("GetYesOrNo", "User"))
{
<div class="form-group">
<label class="control-label">Is it True ?</label>
#Html.DropDownList("miDropDownList", listado)
</div>
<button type="submit">Find</button>
}
Action:
public IActionResult GetYesOrNo(string miDropDownList)
{
//.....
return View();
}
Test result:
And how to bind to the model with dropdownlist,you can see my this reply,it may helpful.

Can not find a way to check or uncheck checkbox in my view

I have a partial view ,which I throw to another view ,In my partial view there is a checkbox which is checked by default I want to change its current (checked/unchecked) option from main view. Here is my partial view code:
<td class="sevenCol" name="sevenCol">
<input type="checkbox" checked/>
</td>
Below shows partial view content:
$("#btnSubmit").click(function () {
var mobnum = $("#mobNo").val();
var message = $("#txtMessage").val();
alert(mobnum);
$.ajax({
url: "SmsSendFromOneToOne",
type: "POST",
data: { contactList: mobnum, message: message },
success: function (data) {
$("#gridGenerate").html(data);
}
});
});
Below verifies checkbox is checked or unchecked but it always returns true so how can I fix this?
$("#sendbtn").click(function () {![enter image description here][1]
var maskId = $("#MASKLIST").val();
var campaignName = $("#campaignName").val();
var dataArray = {};
$(".loadingmessage").show();
$("#gridGenerate tr").each(function (iii, val) {
var trId = $(this).attr("id");
var isChecked = $('td[name=sevenCol]').find('input[type="checkbox"]').is(':checked');
//alert(isChecked);
if (isChecked) {
dataArray[iii] = {
'mobile': $(this).find(".secondCol").text(),
'message': $(this).find(".thirdCol").text(),
'type': $(this).find(".fifthCol").text()
};
}
});
Controller:
[HttpPost]
public ActionResult SmsSendFromOneToOne(string contactList, string message)
{
IList<GridPanel> cellInfoForForm1 = _smsService.GetForm1ForViewing(contactList, message);
return PartialView("partialGridPanel", cellInfoForForm1);
}
Thanks
it is a lot simpler if you put the selector directly on the field. try adding a class to your checkbox
<input type="checkbox" class="mobileCheck" checked/>
then in your script you can replace
var isChecked = $('td[name=sevenCol]').find('input[type="checkbox"]').is(':checked');
with
var isChecked = $('.mobileCheck').is(':checked');
Finally got my answer ,As i am binding a partial view and checkbox exits in it so i have to use jquery .live( events, data, handler(eventObject) )to solve the issue ..
$( selector ).live( events, data, handler );
Again thanks for responding

MVC How to handel submit button on dynamically added partialview

Hi I have just started MVC Programming, so pls excuse my noob question.
I have a Index View with dropdown. And According to the dropdown value, I have added a partial view '_create' in ContentDiv of Index using jquery.
$('#CreateButton').click(function (e) {
$("#ContentDiv").load('/Controller/_Create?Id=' + $("#DropDownList1").val());
});
So, now I am not sure how to handel submit button inside that partialview (_Create)
My _create form looks like:
#using (Html.BeginForm("_Create","controller", FormMethod.Post,
new { id = "addFormData", name="addFormData" }))
{
----------
----------
<p>
<input type="submit" value="Create" />
</p>
}
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult _Create(WorkFieldModel entity, FormCollection p_form)
{
addFormValuetoDB();
return PartialView();
}
And One more thing; how to maintain viewstate of dynamically added partial view after postback.
Any Help will be highly appreciated.
You could use an AJAX request to submit the form to avoid performing a full postback to the server and loosing the context:
$('#CreateButton').click(function (e) {
var data = { id: $("#DropDownList1").val() };
$("#ContentDiv").load('/Controller/_Create', data, function() {
$('#addFormData').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
alert('Thanks for submitting the form');
}
});
return false;
});
});
});
Since your HttpPost controller action returns a PartialView you could use this information in the success callback of the form submit and inject the result somewhere in the DOM.

AJAX Cascading with MVC4

I used the below method for doing Async postback using AJAX. This works fine on clicking submit. But i would like to know, is that possible to call various ActionMethods in a controller via AJAX.
I would like to implement something like cascading dropdown. How to call different ActionMethod via AJAX on dropdown value change?
Here is the code which call only one ActionMethod on submitting form.
View
#{
ViewBag.Title = "Index";
var options = new AjaxOptions()
{
Url = Url.Action("Index", "City"),
LoadingElementId = "saving",
LoadingElementDuration = 2000,
Confirm = "Are you sure you want to submit?"
};
}
<h2>Index</h2>
#using (Ajax.BeginForm(options))
{
<div id="saving">Loading...</div>
#Html.DropDownList("Countries",ViewBag.Countries as SelectList)<input type="submit" />
}
Controller
public ActionResult Index()
{
IEnumerable<SelectListItem> selectListItems = new []
{
new SelectListItem{ Text = "US",Value = "1" }
};
ViewBag.Countries = selectListItems;
return View();
}
public ActionResult GetState(string countryId)
{
IEnumerable<SelectListItem> selectListItems = new[]
{
new SelectListItem { Text = "Tennesse", Value = "1" },
new SelectListItem { Text = "Newyork", Value = "2" }
};
return View();
}
The answer to your first question "is that possible to call various ActionMethods in a controller via AJAX" is a big yes. You may call any action method from your controller through Ajax though the only result generated depends on various things like whether you send a view or partial view or JSON result.
for your next question :
I will be posting some codes
Controller.cs
public JsonResult getCity(string country)
{
var temp = (from cntry in db.Table3.OrderBy(s => s.country)
where (string.Compare(cntry.country, country) == 0)
select cntry.city).ToList();
return Json(temp, JsonRequestBehavior.AllowGet);
}
View
<h1>
Countries</h1>
<select name="countries" class="combo">
<option value=""></option>
#{
foreach (var t in (List<string>)ViewBag.countries)
{
<option value=#t>#t</option>
}
}
</select>
<h1>
State</h1>
<select name="city" class="combo2">
</select>
<div id="tese">
</div>
#*
The following jquery code finds the selected option from country dropdown
and then sends an ajax call to the Home/getcity method
and finally populate it to the city dropdown
*#
<script type="text/javascript">
$('body').on('change', '.combo', function () {
var selectedValue = $(this).val();
alert(selectedValue);
$.get("/Home/getcity", { country: selectedValue }, function (data) {
$("#tese").html(data);
$(".combo2").html("<option value = \"\"></option>")
$.each(data, function (index, value) {
$(".combo2").append("<option value = \"" + value + "\">" + value + "</option>");
});
$(".combo2").html()
});
});
</script>
This will show a dropdown of countries list. Once a country is selected it will render a new dropdown of city list
public JsonResult getCity(string country)
{
var temp = (from cntry in db.Table3.OrderBy(s => s.country)
where (string.Compare(cntry.country, country) == 0)
select cntry.city).ToList();
return Json(temp, JsonRequestBehavior.AllowGet);
}
View
<h1>
Countries</h1>
<select name="countries" class="combo">
<option value=""></option>
#{
foreach (var t in (List<string>)ViewBag.countries)
{
<option value=#t>#t</option>
}
}
</select>
<h1>
State</h1>
<select name="city" class="combo2">
</select>
<div id="tese">
</div>
#*
The following jquery code finds the selected option from country dropdown
and then sends an ajax call to the Home/getcity method
and finally populate it to the city dropdown
*#
<script type="text/javascript">
$('body').on('change', '.combo', function () {
var selectedValue = $(this).val();
alert(selectedValue);
$.get("/Home/getcity", { country: selectedValue }, function (data) {
$("#tese").html(data);
$(".combo2").html("<option value = \"\"></option>")
$.each(data, function (index, value) {
$(".combo2").append("<option value = \"" + value + "\">" + value + "</option>");
});
$(".combo2").html()
});
});
</script>

Ajax.ActionLink parameter from DropDownList

I have the following view part:
<div class="editor-label">
#Html.LabelFor(model => model.Type)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Type, ElangWeb.Helpers.ModelHelpers.GetExerciseTypes())
</div>
I want to have a link which will generate some partialview based on my model's Type property which is an Enum (I return different partial views based on the type),
I've added the following link:
#Ajax.ActionLink("AddExerciseItem",
"AddExerciseItem",
"Exercise",
new { type=#Model.Type},
new AjaxOptions() { HttpMethod="GET", InsertionMode = InsertionMode.InsertBefore, UpdateTargetId="ExerciseItems"})
My controller action is defined as follows:
public ActionResult AddExerciseItem(ExerciseType type)
{
return PartialView("ExerciseItemOption", new ExerciseItemOption());
}
I however does not work because I have the exeption "Object reference not set to an instance of an object" for my Model. How to resolve this issue?
You could use a normal link:
#Html.ActionLink(
"AddExerciseItem",
"AddExerciseItem",
"Exercise",
null,
new { id = "add" }
)
that you could unobtrusively AJAXify:
// When the DOM is ready
$(function() {
// Subscribe to the click event of the anchor
$('#add').click(function() {
// When the anchor is clicked get the currently
// selected type from the dropdown list.
var type = $('#Type').val();
// and send an AJAX request to the controller action that
// this link is pointing to:
$.ajax({
url: this.href,
type: 'GET',
// and include the type as query string parameter
data: { type: type },
// and make sure that you disable the cache because some
// browsers might cache GET requests
cache: false,
success: function(result) {
// When the AJAX request succeeds prepend the resulting
// markup to the DOM the same way you were doing in your
// AJAX.ActionLink
$('#ExerciseItems').prepend(result);
}
});
return false;
});
});
Now your AddExerciseItem controller action could take the type parameter:
public ActionResult AddExerciseItem(string type)
{
...
}