How to form query string? - asp.net-mvc-4

I am using the grid source code from this website:
http://gridmvc.azurewebsites.net/
but I don't understand how the query string is formed for his custom columns. On the link I have provided there is an edit column, if you hover over the link you can see the hyperlink with the query string ID. I have used this source code but there is no query string for me.
Controller code
#region PartialViews
[ChildActionOnly]
public ActionResult RenderGrid()
{
DataLayer.RepositoryClient RC = new RepositoryClient();
var People = RC.GetPeople();
return PartialView("~/Views/Client/PartialViews/P_PersonGrid.cshtml", People);
}
#endregion
I get a list of people from entity framework. Then I use a list of models in my partial view.
Partial view
#model List<Models.modelPeopleGrid>
#using GridMvc.Html
#{
ViewBag.Title = "Person records";
}
<div>
#Html.Label("Search for person")
<input type="text" onkeyup="activateSearch()" id="txtSearch" style="width:150px";/>
</div>
<div class="grid-wrap" style="float:left">
#Html.Grid(Model).Named("peopleGrid").Columns(columns =>
{
columns.Add(m => m.Firstname).Titled("Firstname").Filterable(true);
columns.Add(m => m.Surname).Titled("Surname").Filterable(true);
columns.Add(m => m.DateOfBirth).Titled("DateOfBirth").Filterable(true);
columns.Add(m => m.Address).Titled("Address").Filterable(true);
columns.Add(m => m.Borough).Titled("Borough").Filterable(true);
columns.Add(m => m.PersonID).Encoded(false).Sanitized(false).SetWidth(30).RenderValueAs(
#<b>
#Html.ActionLink("Edit person details", "EditPerson", "Index")
</b>);
columns.Add()
.Encoded(false)
.Sanitized(false)
.SetWidth(30)
.RenderValueAs(m =>
#<b>
#Html.ActionLink("Add/remove claims", "EditClaim", "Index")
</b>);
}).WithPaging(20)
</div>
<div class="rowValues" style="float:right"></div>
<script>
$(function () {
pageGrids.peopleGrid.onRowSelect(function (e) {
$(".rowValues").html(
"<h4>Full details of person:</h4>" +
"Firstname: " + e.row.Firstname + "<br />" +
"Surname: " + e.row.Surname + "<br />" +
"DateOfBirth: " + e.row.DateOfBirth + "<br />" +
"Address: " + e.row.Address + "<br />" +
"Borough: " + e.row.Borough + "<br />"
);
});
});
</script>
<script type="text/javascript">
function activateSearch() {
var value = $("#txtSearch").val();
$.ajax({
url: "Client/GetPeople",
dataType: 'html',
type: "GET",
data: { Name: value },
success: function (data) {
$('.webgrid').empty().html(data);
},
error: function () {
alert("error");
}
});
}
</script>
I don't know how to get a query string formed for this line of code:
columns.Add(m => m.PersonID).Encoded(false).Sanitized(false).SetWidth(30).RenderValueAs(
#<b>
#Html.ActionLink("Edit person details", "EditPerson", "Index")
</b>);
I tried html object attributes as the fourth parameter of actionlink but I was getting a red swiggly for some reason.
Anyone know how to answer my problem?

As seen in the example on the website you've linked to, the RenderValueAs method takes a lambda expression where the parameter represents the current model for the row.
I tried html object attributes as the fourth parameter of actionlink
but I was getting a red swiggly for some reason.
Usually Razor Intellisense and syntax highlighting in Visual Studio is very buggy. Never trust it. The fact that you are getting red squiggles in a Razor page doesn't mean that you have an error in your syntax. In most cases it means that it is the syntax highlighter that simply doesn't understand the syntax. The only reliable thing is to run your application and see if it works.
So with this in mind you may try:
columns
.Add(m => m.PersonID)
.Encoded(false)
.Sanitized(false)
.SetWidth(30)
.RenderValueAs(m =>
#<b>
#Html.ActionLink(
linkText: "Edit person details",
actionName: "EditPerson",
controllerName: "Index", // <-- Huh, Index looks like an action name, double check that
routeValues: new { id = m.PersonID },
htmlAttributes: null
)
</b>
);
Notice how I have used explicit parameter names to make the code more readable and avoid any ambiguities with the gazzillions of overloads of the ActionLink method that the designers of the framework provided us.

Related

Vue JS fire a method based on another method's output unique ID

I'm trying to render a list of notes and in that list I would like to include the note's user name based on the user_id stored in the note's table. I have something like this, but at the moment it is logging an error stating Cannot read property 'user_id' of undefined, which I get why.
My question is, in Vue how can something like this be executed?
Template:
<div v-for="note in notes">
<h2>{{note.title}}</h2>
<em>{{user.name}}</em>
</div>
Scripts:
methods:{
fetchNotes(id){
return this.$http.get('http://api/notes/' + id )
.then(function(response){
this.notes = response.body;
});
},
fetchUser(id){
return this.$http.get('http://api/user/' + id )
.then(function(response){
this.user = response.body;
});
}
},
created: function(){
this.fetchNotes(this.$route.params.id)
.then( () => {
this.fetchUser(this.note.user_id);
});
}
UPDATE:
I modified my code to look like the below example, and I'm getting better results, but not 100% yet. With this code, it works the first time it renders the view, if I navigate outside this component and then back in, it then fails...same thing if I refresh the page.
The error I am getting is: [Vue warn]: Error in render: "TypeError: Cannot read property 'user_name' of undefined"
Notice the console.log... it the returns the object as expected every time, but as I mentioned if refresh the page or navigate past and then back to this component, I get the error plus the correct log.
Template:
<div v-for="note in notes">
<h2>{{note.title}}</h2>
<em>{{note.user.user_name}}</em>
</div>
Scripts:
methods:{
fetchNotes(id){
return this.$http.get('http://api/notes/' + id )
.then(function(response){
this.notes = response.body;
for( let i = 0; i < response.body.length; i++ ) {
let uId = response.body[i].user_id,
uNote = this.notes[i];
this.$http.get('http://api/users/' + uId)
.then(function(response){
uNote.user = response.body;
console.log(uNote);
});
}
});
},
}
It looks like you're trying to show the username of each note's associated user, while the username comes from a different data source/endpoint than that of the notes.
One way to do that:
Fetch the notes
Fetch the user info based on each note's user ID
Join the two datasets into the notes array that your view is iterating, exposing a user property on each note object in the array.
Example code:
let _notes;
this.fetchNotes()
.then(notes => this.fetchUsers(notes))
.then(notes => _notes = notes)
.then(users => this.joinUserNotes(users, _notes))
.then(result => this.notes = result);
Your view template would look like this:
<div v-for="note in notes">
<h2>{{note.title}}</h2>
<em>{{note.user.name}}</em>
</div>
demo w/axios
UPDATE Based on the code you shared with me, it looks like my original demo code (which uses axios) might've misled you into a bug. The axios library returns the HTTP response in a data field, but the vue-resource library you use returns the HTTP response in a body field. Attempting to copy my demo code without updating to use the correct field would cause the null errors you were seeing.
When I commented that axios made no difference here, I was referring to the logic shown in the example code above, which would apply to either library, given the field names are abstracted in the fetchNotes() and fetchUsers().
Here's the updated demo: demo w/vue-resource.
Specifically, you should update your code as indicated in this snippet:
fetchInvoices(id) {
return this.$http.get('http://localhost/php-api/public/api/invoices/' + id)
// .then(invoices => invoices.data); // DON'T DO THIS!
.then(invoices => invoices.body); // DO THIS: `.data` should be `.body`
},
fetchCustomers(invoices) {
// ...
return Promise.all(
uCustIds.map(id => this.$http.get('http://localhost/php-api/public/api/customers/' + id))
)
// .then(customers => customers.map(customer => customer.data)); // DON'T DO THIS!
.then(customers => customers.map(customer => customer.body)); // DO THIS: `.data` should be `.body`
},
Tony,
Thank you for all your help and effort dude! Ultimately, with the help from someone in the Vue forum, this worked for me. In addition I wanted to learn how to add additional http requests besides the just the user in the fetchNotes method - in this example also the image request. And this works for me.
Template:
<div v-if="notes.length > 0">
<div v-if="loaded === true">
<div v-for="note in notes">
<h2>{{note.title}}</h2>
<em>{{note.user.user_name}}</em>
<img :src="note.image.url" />
</div>
</div>
<div v-else>Something....</div>
</div>
<div v-else>Something....</div>
Script:
name: 'invoices',
data () {
return {
invoices: [],
loaded: false,
}
},
methods: {
fetchNotes: async function (id){
try{
let notes = (await this.$http.get('http://api/notes/' + id )).body
for (let i = 0; notes.length; i++) {
notes[i].user = (await this.$http.get('http://api/user/' + notes[i].user_id)).body
notes[i].image = (await this.$http.get('http://api/image/' + notes[i].image_id)).body
}
this.notes = this.notes.concat(notes)
}catch (error) {
}finally{
this.loaded = true;
}
}

MVC Failed to load resource: the server responded with a status of 500 (Internal Server Error)

I have problem with my first MVC project. I'm trying to change values of DropDownList of surnames when select DropDownList of doctor types. I think my action is working. But I cannot use result in view.
Here my codes:
$(function () {
$('select#mCB').change(function () {
var docId = $(this).val();
$.ajax({
dataType: 'json',
data: 'spec=' + docId,
method: 'GET',
url: 'LoadDoctors',
success: function (data) {
$.each(data, function (key, Docs) {
$('select#shCB').append('<option value="0">Select One</option>');
$.each(Docs, function (index, docc) {
$('select#shCB').append(
'<option value="' + docc.Id + '">' + docc.Name + '</option>');
});
});
},
error: function (docID) {
alert(' Error !');
}
});
});
});
Actions:
public static List<Docs> GetDoctorBySpec(string spec)
{
List<Docs> list = new List<Docs>();
string query = "select ID, Familiyasi, Speciality from Doktorlar where Speciality=#spec";
SqlConnection Connection = new SqlConnection(DataBase.ConnectionString);
Connection.Open();
SqlCommand cmd = new SqlCommand(query, Connection);
cmd.Parameters.Add("#spec", spec);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
list.Add(new Docs
{
Id = dr.GetString(0),
Name = dr.GetString(1)
});
}
return list;
}
enter code here
enter code here
[HttpGet]
public ActionResult LoadDoctors(string spec)
{
List<Docs> list = DoctorsService.GetDoctorBySpec(spec);
if (list == null)
{
return Json(null);
}
return Json(list);
}
And here my DropDownLists:
<div class="editor-label">
#Html.LabelFor(model => model.DoktorTuri)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.DoktorTuri, new SelectList(ViewBag.Vrachlar), new { #id = "mCB", #class = "vrachlar" })
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Shifokori)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Shifokori, Enumerable.Empty<SelectListItem>(), new { #id = "shCB", #class = "vrachlar" })
</div>
Where is my mistake? Thanks for answers
A 500 (Internal Server Error) almost always means that your throwing an exception on the server. Best guess is in your case it's because your method
DoctorsService.GetDoctorBySpec(spec);
does not accept null as a parameter and the value of spec is null because your never pass it value to the controller. As stann1 has noted your ajax option needs to be
data: {spec: docId},
In addition, you do not specify the JsonRequestBehavior.AllowGet parameter which means the method will fail.
All of this can be easily determined by debugging your code, both on the server and by using your browser tools (in particular the Network tab to see what is being sent and received along with error messages)
However this is only one of many problems with your code.
Firstly, unless Docs contains only 2 properties (the values you need for the option's value attribute and display text), your unnecessarily wasting bandwidth and degrading performance by sending a whole lot of data to the client which is never used. Instead, send a collection of anonymous objects
[HttpGet]
public ActionResult LoadDoctors(string spec)
{
List<Docs> list = DoctorsService.GetDoctorBySpec(spec);
if (list == null)
{
return Json(null, JsonRequestBehavior.AllowGet);
}
var data = list.Select(d => new
{
Value = d.Id,
Text = d.Name
});
return Json(data, JsonRequestBehavior.AllowGet);
}
Next, your script will only ever generate multiple <option value="0">Select One</option> elements (one for each item in the collection) because data in $.each(data, function (key, Docs) { is your collection, and Docs is the item in the collection. Your second $.each() function will never produce anything because Docs is not a collection.
You script should be (note I have use the short version $.getJSON() rather than the longer $.ajax() and also used the default id attributes generated by the html helpers - its not clear why you would want to change the id's using new { id = "mCB" }?)
var url = '#Url.Action("LoadDoctors")'; // never hard code your url's
var shifokori = $('#Shifokori'); // cache it
$('#DoktorTuri').change(function () {
$.getJSON(url, { spec: $(this).val() }, function(data) {
if (!data) { // only necessary depending on the version of jquery
// oops
}
// clear existing options and append empty option with NULL value (not zero)
// so validation will work
shifokori.empty().append($('<option></option>').val('').text('Select One'));
$.each(data, function (index, doc) {
shifokori.append($('<option></option>').val(doc.Value).text(doc.Text));
});
}).fail(function (result) {
// oops
});
});
The data param of the call needs to be a Javascript object literal:
$.ajax({
dataType: 'json',
data: {spec: docId},
method: 'GET',
....
});
Also, try to debug your controller and use a rest extension (or Fiddler) to test the payload, you would catch such error easily yourself ;)

Mvc4 having 2 forms in one view

So i'm building a simple mvc4 application, I have created all base models for the creation of the DB, from these classes I could naturally create basic controllers with their matching views.
Now my problem: I have the basic create actionresult + view and in this view I wanted that the user would be able to select some values from a dropdownlist which would make creation of new objects simpler.
I tried to achieve this with a second form in my view (the first one is the basic create form) now if I want to use these dropdowns (they filter each other(so first the user must specify a continent, then the dropdown of the countries only shows countries from that continent and after he specifies a country the region dropdown gets updated :) )) the submit of the basic view is always automatically called.
so making the dropdowns update themselves isn't the problem :s it's that the form for the create automatically validates when the dropdowns are updated
this is the controller where the dropdowns filter each other
//
// GET: /FederationCenter/Create
public ActionResult Create(string searchRegion, string searchCountry, string searchContinent)
{
var countries = from c in db.Countries select c;
if (!String.IsNullOrEmpty(searchContinent))
{
Continent searchContinentEnumValue = (Continent)Enum.Parse(typeof(Continent), searchContinent);
countries = from c in db.Countries where ((int)c.Continent).Equals((int)searchContinentEnumValue) select c;
}
var regions = from r in db.Regions where r.Country.Name.Equals(searchCountry) select r;
ViewBag.searchContinent = new SelectList(Enum.GetNames(typeof(SchoolCup.Domain.Continent)));
ViewBag.searchCountry = new SelectList(countries, "Name", "Name");
ViewBag.searchRegion = new SelectList(regions, "Name", "Name");
return View();
}
//
// POST: /FederationCenter/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(NSSF nssf, string searchRegion, string searchCountry, string searchContinent)
{
var countries = from c in db.Countries select c;
if (!String.IsNullOrEmpty(searchContinent))
{
Continent searchContinentEnumValue = (Continent)Enum.Parse(typeof(Continent), searchContinent);
countries = from c in db.Countries where ((int)c.Continent).Equals((int)searchContinentEnumValue) select c;
}
var regions = from r in db.Regions where r.Country.Name.Equals(searchCountry) select r;
ViewBag.searchContinent = new SelectList(Enum.GetNames(typeof(SchoolCup.Domain.Continent)));
ViewBag.searchCountry = new SelectList(countries, "Name", "Name");
ViewBag.searchRegion = new SelectList(regions, "Name", "Name");
if (ModelState.IsValid)
{
var naam = Request["searchRegion"];
Region creatie = (from c in db.Regions where c.Name.Equals(naam) select c).SingleOrDefault();
nssf.ISFId = 1;
nssf.RegionId = creatie.RegionId;
db.NSSFs.Add(nssf);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(nssf);
}
and this is my view
#model SchoolCup.Domain.POCO.NSSF
#{
ViewBag.Title = "Create";
}
<h2>Create NSSF</h2>
<div>
#using (Html.BeginForm(null, null, FormMethod.Post, new { name = "form" }))
{
#Html.AntiForgeryToken()
#Html.DropDownList("searchContinent", null, "-- All continents --", new { onchange = "sendForm()" })
#Html.DropDownList("searchCountry", null, "-- All countries --", new { onchange = "sendForm()" })
#Html.DropDownList("searchRegion", null, "-- All regions --", new { onchange = "sendForm()" })
<>
<input type="submit" name= value="Search" />
}
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>NSSF</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
some more inputs
</fieldset>
<p>
<input type="submit" value="Create" />
#Html.ActionLink("Back to List", "Index", null, new { #class = "button" })
</p>
}
#section Scripts {
<script type="text/javascript">
function sendForm() {
document.form.submit()
}
</script>
}
I've been looking for at least a day and I don't know how to solve this
with regards
Alexander
How about either (1) using JQuery and loading the drop-down with a Partial view returned by your controller or (2) you could have an AJAX call that would return your values as a JSON object mapped from your entity and you can render them in the drop-down. This way your form won't be submitted every time you update a drop-down.
The first solution might look something like this:
JQUERY
<script>
$("#searchContinent").change(function() {
$("#searchCountry").load("/YourController/GetCountries", { 'continentId': $(this).val() },
function (response, status, xhr) {
if (status == "error") {
alert("An error occurred while loading the results.");
}
});
});
</script>
#Html.DropDownList("searchContinent", null, "-- All continents --" })
<div id="searchCountry">
<!--the newly created drop-down will be placed here-->
</div>
(EDIT)
For Javascript you might try something like this:
YOUR CURRENT VIEW
#Html.DropDownList("searchContinent", null, "-- All continents --", new { onchange = "getCountries(this)" })
<div id="searchCountry">
<!--the newly created drop-down will be placed here-->
</div>
<script>
function getCountries(input){
var selectedValue = input.options[input.selectedIndex].value;
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "YourController/GetCountries?continentId="+selectedValue, false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
document.getElementById("searchCountry").innerHTML=serverResponse ;
}
</script>
DISCLAIMER: This I have never tried so if it's wrong don't hesitate to let me know and correct it if necessary
(END EDIT)
CONTROLLER
public ActionResult GetCountries(string continentId)
{
/*Get your countries with your continentId and return a Partial View with a list of
countries as your model*/
return PartialView(countryList);
}
GetCountries VIEW
#model IEnumerable<SchoolCup.Domain.Country>
#Html.DropDownListFor( 0, Model)

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>

how to do postback on changing dropdownlist selected item in mvc4

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