Submit multiple radio button values with one button ASP.NET MVC - javascript

There are three groups of radio buttons on my page and I want to submit each of their values with one button.
<table>
<tr>
<td>
#Html.RadioButton("rating1", "yes", true) Yes
#Html.RadioButton("rating1", "no", false) No
#Html.RadioButton("rating1", "maybe", false) Maybe
</td>
</tr>
<tr>
<td>
#Html.RadioButton("rating2", "yes", true) Yes
#Html.RadioButton("rating2", "no", false) No
#Html.RadioButton("rating2", "maybe", false) Maybe
</td>
</tr>
<tr>
<td>
#Html.RadioButton("rating3", "yes", true) Yes
#Html.RadioButton("rating3", "no", false) No
#Html.RadioButton("rating3", "maybe", false) Maybe
</td>
</tr>
</table>
I want to send a dictionary as a parameter to the controller action so I can retrieve the values for each rating.
The controller looks like this:
public ActionResult Rate(Guid uniqueId, Dictionary<Guid, string> ratings)
{
[...]
}
I have tried:
<input type="submit" value="Send Ratings" onclick="#Url.Action("Rate", "Controller", new {new Dictionary<string,string> {{"rating1", "yes"}, {"rating2", "no"}, {"rating3", "maybe"}})"></input>
but passing a Dictionary as a RouteValue like that is not allowed.
How do I send all 3 radio button [name,value] pairs to the action with one button /submit? Also, should all three groups be in the same form or separate forms?
I am open to using javascript, but would prefer using Razor HTML helpers.
Thanks

Model
public class ExampleViewModel
{
public ExampleViewModel()
{
Answers = new Dictionary<string, string>();
Questions = new List<KeyValuePair<string, List<string>>>();
}
public Dictionary<string, string> Answers { get; set; }
public List<KeyValuePair<string, List<string>>> Questions { get; set; }
public ExampleViewModel Add(string key, string[] value)
{
Questions.Add(new KeyValuePair<string, List<string>>(key, value.ToList()));
return this;
}
}
Controller
[HttpGet]
public ActionResult Index()
{
ExampleViewModel model = new ExampleViewModel();
model.Add("rating1",new[] { "Yes" ,"No", "Maybe"});
model.Add("rating2", new[] { "Yes", "No", "Maybe" });
model.Add("rating3", new[] { "Yes", "No", "Maybe" });
return View(model);
}
[HttpPost]
public ActionResult Index(ExampleViewModel model)
{
//model.Answers is the dictionary of the values submitted
string s = model.Answers.Count.ToString();
return View();
}
View
#model ExampleViewModel
#using (Html.BeginForm())
{
<table class="table table-bordered table-striped">
#for(int i=0;i<Model.Questions.Count;i++)
{
var question = Model.Questions[i];
<tr>
<td>
#foreach (var answer in question.Value)
{
<input type="hidden" name="Model.Answers[#question.Key].Key" value="#question.Key" />
<input type="hidden" name="Model.Answers.Index" value="#question.Key" />
#Html.RadioButton("Model.Answers[" + question.Key+"].Value", answer, false) #answer
}
</td>
</tr>
}
<tr>
<td>
<input type="submit" class="btn btn-primary" value="Submit" />
</td>
</tr>
</table>
}
model.Answers will hold the dictionary containing the submitted values

You can use FormCollection for gating your radio button value on your post.
you have to simply write var variable = f["rating1"]; in your post method and u get your selected radio button value on post method,
public ActionResult Rate(Guid uniqueId,FormCollection f)
{
var variable1 = f["rating1"];
var variable2 = f["rating2"];
var variable3 = f["rating3"];
[...]
}

Related

Actionlink rowindex stored to a C# get set

I have an ActionLink that is deleting a row from a html table and should be updating the controller. The problem however is that the information of the row that the button is on isn't being shared with the controller once the button is clicked.
<table id="LansingData" class="table">
<thead>
<tr>
<th>Action</th>
<th>Row ID</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Records)
{
<tr id="#item.RowIndex">
<td>#Html.ActionLink("Delete", "Delete", new { id = item.RowIndex }, new { onclick = "return confirm('Are you sure you want to delete this user?');", #class = "delete-button" })</td>
<td>#item.RowIndex</td>
</tr>
}
</tbody>
</table>
This is my controller that is performing the delete.
public ActionResult Delete(int? rowID)
{
if (rowID == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
LansingMileage lansing = db.LansingMileages.Find(rowID);
if (lansing == null)
{
return HttpNotFound();
}
return View(lansing);
}
//POST:
[HttpPost, ActionName("Index")]
[OnAction(ButtonName = "Delete")]
//[ValidateAntiForgeryToken]
public ActionResult Delete(int rowID)
{
LansingMileage lansing = db.LansingMileages.Find(rowID);
db.LansingMileages.Remove(lansing);
db.SaveChanges();
return RedirectToAction("Index");
}
The desired result will be for the link to post to the controller with the rowID of the whatever link was selected.
Looks like a naming issue. The parameter is called id in the view and (most likely) in route definition, but the controller expects rowID. Just rename this last one to be id too:
public ActionResult Delete(int? id)
Model binding in MVC is done by name, so make sure posted parameters always match those expected on the server side.

How do I retrieve a viewmodel from another viewmodel?

I have this ViewModel which incorporates 3 other viewmodels and a list:
public class GroupPageViewModel{
public string GroupName { get; set; }
public GroupSelectViewModel _groupSelectVM {get; set;}
public List<User> _users { get; set; }
public ViewModelStudent _studentVM { get; set; }
public ViewModelGroupMembers _groupMembersVM { get; set; }
}
In the view I can access each of these sub-ViewModels by Model._groupSelectVM, each of the sub-ViewModels are associated with a partial view. The problem arises when I need to refresh just one or two partial views, I'm not sure how to access the inner ViewModels returned in an Ajax success, and as I'm relatively new to MVC and asp.net in general. And I literally know next to nothing about JavaScript, jquery or Ajax.
How would I go about getting a specific ViewModel from the main ViewModel in an Ajax success?
This is just one example for the clarification requested all the others are pretty much the same (although some of them might need to update mutliple partial views -
From the controller:
[HttpPost]
public ActionResult Index(string groupChoice = "0", string newGroup = "")
{
string groupName = "";
if (groupChoice == "0" && newGroup != "")
{
if (ModelState.IsValid)
{
Group group = new Group
{
GroupName = newGroup,
Active = true
};
db.Groups.Add(group);
db.SaveChanges();
PopulateLists();
}
}
else if (groupList == null)
{
groupList = (List<SelectListItem>)Session["groupList"];
Session["groupName"] = groupName = groupList.Where(m => m.Value == groupChoice).FirstOrDefault().Text;
MembersInSpecificGroup(groupName, groupMembers, groupMembersList);
groupPageVM._groupMembersVM = groupMembers;
}
return View("GroupSelection", groupPageVM);
}
The script:
$(document).ready(function () {
$('#selectedGroup').change(function () {
var data = {
groupChoice: $('#selectedGroup').val()
};
var groupChoice = $('#selectedGroup').val();
$.ajax({
url: '/Group/Index/',
type: 'POST',
data: { groupChoice: groupChoice },
success: function (data) {
setTimeout(function () {
delayGroupSuccess(data);
}, delay);
}
});
})
});
function delayGroupSuccess(data) {
$("#groupSelect").html(data);
}
The main page:
#model EMBAProgram.ViewModels.GroupPageViewModel
#{ Layout = "~/Views/Shared/_Layout.cshtml"; }
<h2>Group Selection</h2>
<div class="row" id="groupSelect">
#{ Html.RenderPartial("_GroupSelect", Model._groupSelectVM);}
</div>
<hr size="5" />
<div style="display: flex;">
<div>
#{Html.RenderPartial("_Students", Model._studentVM);}
</div>
<div>
#{ Html.RenderPartial("_GroupMembers", Model._groupMembersVM);}
</div>
<div>
#{ Html.RenderPartial("_Users", Model._users);}
</div>
<br style="clear: left;" />
</div>
The partial view:
#model EMBAProgram.ViewModels.ViewModelGroupMembers
<div class="table-responsive" id="groupResults">
<table class="table table-condensed table-responsive">
<thead>
<tr>
<th>#Html.DisplayName("M-Number")</th>
<th>#Html.DisplayName("Name")</th>
<th>#Html.DisplayName("Student")</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model._groupVM) {
<tr>
<td>#Html.DisplayFor(m => item.MNumber)</td>
<td>#Html.DisplayFor(m => item.Name)</td>
<td>#Html.DisplayFor(m => item.Student)</td>
</tr>
}
</tbody>
</table>
</div>
Basically I need to be able pull the ViewModel for the partial view from the main ViewModel (which I believe is what is being returned in the Ajax,) and refresh the partial view.
I removed the original answer, it's available in the edit log if folks want to see it I think. But it was taking up too much space and was incorrect.
You can return multiple partial views, I thought it was a built in way to get them to a string (I was in a rush in my comment), but I've got a working example.
In the controller I have the following:
public ActionResult Index()
{
var model = new TestViewModel
{
Students = GetStudents(),
Categories = GetCategories(),
Groups = GetGroups()
};
return View("Index", model);
}
// Returns multiple partial views as strings.
public ActionResult StudentsAndGroups()
{
return Json(new
{
Students = RenderRazorViewToString("_Students", GetStudents()),
Groups = RenderRazorViewToString("_Groups", GetGroups())
}, JsonRequestBehavior.AllowGet);
}
// Creates a string from a Partial View render.
private string RenderRazorViewToString(string viewName, object model)
{
ControllerContext.Controller.ViewData.Model = model;
using (var stringWriter = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ControllerContext.Controller.ViewData, ControllerContext.Controller.TempData, stringWriter);
viewResult.View.Render(viewContext, stringWriter);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return stringWriter.GetStringBuilder().ToString();
}
}
I have my main index view that looks like the following:
<button class="refresh">Refresh</button>
<div class="row">
<div class="col-md-4 students">
#{
Html.RenderPartial("_Students", Model.Students);
}
</div>
<div class="col-md-4">
#{
Html.RenderPartial("_Category", Model.Categories);
}
</div>
<div class="col-md-4 groups">
#{
Html.RenderPartial("_Groups", Model.Groups);
}
</div>
</div>
#section scripts
{
<script type="text/javascript">
$(".refresh").click(function () {
$.get("/Home/StudentsAndGroups", function (d) {
$(".students").html(d.Students);
$(".groups").html(d.Groups);
})
});
</script>
}
The controller action StudentsAndGroups turns two partial views into strings. From there, the javascript calls that view and accesses the elements and returns them.
Helper method for rendering a view as a string was found here: https://stackoverflow.com/a/34968687/6509508

RadioButtonFor in mvc shows required validation even though not applied required validation

I have one view in which I put two radio button for attribute in my model
I just put data annotation for other field but not the radiobutonfor field but steel it show required validation.Below is my code.I the attribute is int type in model.I used javascript unobtrusive library inn view as well.
<td>
<label>#Html.RadioButtonFor(m => m.OneToOne, 1) Hours </label>
<label>#Html.RadioButtonFor(m => m.OneToOne, 2) Unit </label>
</td>
I am using Html.begin from to post this value.
The RadioButtonFor helper method generates html markup for the radio button input with data-val-required attribute unless you specify the property as nullable type! The jQuery validate plugin does validation on this input because of the existence of this attribute.
If you do not want client side validation on this input, You should change the property type from int to nullable int(int?).
public class YourViewModel
{
// Other properties
public int? OneToOne { set; get; }
}
If radio buttons are not required to select, I personally like to use mutually exclusive checkboxes.
Mainly, if a user accidental selects a radio button, s/he won't be able to uncheck it back unless the user refreshes the entire page. I feel like it is really annoying.
Sample at jsfiddle.net
Model
public class ViewModel
{
public bool OneToOneHours { get; set; }
public bool OneToOneUnit { get; set; }
}
View
#using (Html.BeginForm("Index", "Home", null, FormMethod.Post))
{
<div class="form-control">
#Html.CheckBoxFor(model => model.OneToOneHours, new {#class = "mutually-exclusive"}) Hours
#Html.CheckBoxFor(model => model.OneToOneUnit, new {#class = "mutually-exclusive"}) Unit
</div>
<button id="btnSubmit" type="submit">Submit</button>
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$('input.mutually-exclusive').click(function () {
var checkedState = $(this).val();;
$('input.mutually-exclusive').attr("checked", false);
$(this).prop("checked", checkedState);
});
</script>
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(ViewModel model)
{
int? oneToOne;
if (model.OneToOneHours)
oneToOne = 1;
else if (model.OneToOneUnit)
oneToOne = 2;
return View(model);
}
}

Refreshing ViewModel and view after AJAX call

I'm trying to create a table with child rows (always one child per row) acting as details section. In this details section users will be able to see a log history, and will also have the ability to input a specific log. Upon inputting a new log and clicking on the "Add" button, the log history should update and show the newly added event.
I have the following AJAX call that will be used to add a log and should refresh the details section, triggered after clicking on the "Add" button mentioned above:
$('#addLog').click(function () {
formData = {
logType: logType.value, // Parameter to add a new log
logComments: logComments.value, // Parameter to add a new log
agent: agent.value // Parameter to add a new log
}
$.ajax({
url: '#Url.Action("AddLog", "AgentUser")',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(formData),
cache: false,
success: function (data) {
// Here I should refresh the the details section
// and clear the logType and logCommands inputs
}
});
});
In my controller:
[HttpPost]
public ActionResult AddLog(string logType, string logComments, string agent, AgentUserValidatePhoneIndexViewModel vm)
{
DoDbStuff();
// Here I need to update the view model and view without having to
// refresh the page, so that it shows the recently added event.
return View(vm);
}
My ViewModel:
public class AgentUserValidatePhoneIndexViewModel
{
public IEnumerable<AgentUserWithoutValidPhone> AgentUserWithoutValidPhoneList { get; set; }
}
My Model:
public class AgentUserWithoutValidPhone
{
private string phone;
private DateTime creationDate;
public string Agent { get; set; }
public string Phone
{
get
{
return phone;
}
set
{
phone = PhoneNumberUtil.GetInstance().Parse("+" + value, String.Empty).NationalNumber.ToString();
}
}
public DateTime CreationDate
{
get
{
return creationDate;
}
set
{
creationDate = value;
TimeSpan timeSpan = (DateTime.Now) - creationDate;
TimeGoneBy = (timeSpan.Days != 0 ? timeSpan.Days + "d " : String.Empty) + timeSpan.Hours + "h";
}
}
public string TimeGoneBy { get; set; }
public DateTime LastLogEventDate { get; set; }
public LogEventTypePhone LastLogEvent { get; set; }
public IEnumerable<AgentUsersLog> EventList { get; set; }
}
My view:
#foreach (var agentUser in Model.AgentUserWithoutValidPhoneList)
{
<tr data-toggle="collapse" data-target="#details" class="accordion-toggle">
<td>
<button class="btn btn-default btn-sm"><span class="glyphicon glyphicon-collapse-down"></span></button>
</td>
<td>
#agentUser.Agent
</td>
<td>
#agentUser.Phone
</td>
<td>
#agentUser.CreationDate
</td>
<td>
#agentUser.TimeGoneBy
</td>
<td>
#agentUser.LastLogEventDate
</td>
<td>
#agentUser.LastLogEvent.GetDescription()
</td>
</tr>
<tr>
<td colspan="12" class="hiddenRow" id="">
<div class="accordian-body collapse" id="details">
<table class="table table-striped">
<thead>
<tr>
<input type="hidden" id="agent" value='#agentUser.Agent'>
<td>
#Html.DropDownList("LogEventTypePhone", EnumHelper.GetSelectList(typeof(Enums.LogEventTypePhone)), "Select log event",
new
{
id = "logType",
#class = "form-control"
})
</td>
<td colspan="2">
<input type="text" class="form-control" placeholder="Comments" id="logComments">
</td>
<td>
<a href="#" class="btn btn-default btn-sm" id="addLog">
<i class="glyphicon glyphicon-plus"></i>
</a>
</td>
</tr>
<tr>
<th>Event date</th>
<th>Event type</th>
<th>Comments</th>
<th>User</th>
</tr>
</thead>
<tbody>
#foreach (var e in agentUser.EventList)
{
<tr>
<td>#e.Date</td>
<td>#(((Enums.LogEventTypePhone)e.Subtype).GetDescription())</td>
<td>#e.Comments</td>
<td>#e.AspNetUsers.UserName</td>
</tr>
}
</tbody>
</table>
</div>
</td>
</tr>
}
How do I pass my ViewModel into my controller action, together with the parameters? Right now it's empty by the time I get to the action. I need to pass it into the action, interact with the DB, update the ViewModel, return to the View and have it updated with the current ViewModel.
I've never done what I'm trying to do here and I'm confused about it. Not sure if it's even possible, or maybe I should use several ViewModels.
There is no need to pass the view model to the controller and back again (it would just unnecessarily degrade performance). If your just wanting to add a new row based on the values you post to your controller method, then create a anonymous object (or a new instance of AgentUsersLog) containing the values to be shown in the new row, return it as json and update the DOM by adding a new <tr> element.
There are a few other issues with you code including the fact your creating invalid html (duplicate id attributes) in your foreach loops. Remove the id attributes and use class names instead in conjunction with relative selectors (the code you have shown will only ever handle the .click() event of the first link with id="addLog"). You view code should be
#foreach (var agentUser in Model.AgentUserWithoutValidPhoneList)
{
<tr data-toggle="collapse" data-target=".details" class="accordion-toggle">
....
</tr>
<tr>
<td colspan="12" class="hiddenRow">
<div class="accordian-body collapse details"> // use class name
<table class="table table-striped">
<thead>
<tr>
<td>
<input type="hidden" class="agent" value='#agentUser.Agent'> // must be inside a td element
#Html.DropDownList("LogEventTypePhone", EnumHelper.GetSelectList(typeof(Enums.LogEventTypePhone)), "Select log event", new
{
id = "", // remove id
#class = "form-control logType" // add class name
})
</td>
<td colspan="2">
<input type="text" class="form-control logComments" placeholder="Comments"> // use class name
</td>
<td>
<a href="#" class="btn btn-default btn-sm addLog"> // use class name
<i class="glyphicon glyphicon-plus"></i>
</a>
</td>
</tr>
<tr>
....
</tr>
</thead>
<tbody>
#foreach (var e in agentUser.EventList)
{
....
}
</tbody>
</table>
</div>
</td>
</tr>
}
And the script becomes
var url = '#Url.Action("AddLog", "AgentUser")';
$('.addLog').click(function () {
var table = $(this).closest('table');
var logType = table.find('.logType').val();
var logComments = table.find('.logComments').val();
var agent = table.find('.agent').val();
$.post(url, { logType: logType, logComments: logComments, agent: agent }, function(data) {
var row = $('<tr></tr>');
row.append($('<td></td>').text(data.Date));
.... // add other cells for data.Subtype, data.Comments and data.UserName
table.children('tbody').append(row);
});
});
Then in the controller
[HttpPost]
public JsonResult AddLog(string logType, string logComments, string agent)
{
DoDbStuff();
// Build the data to return
var data = new
{
Date = .... ,
Subtype = .... ,
Comments = ..... ,
UserName = ....
};
return Json(data);
}
You can acheive this by creating child object. Lets assume the model "AgentUserValidatePhoneIndexViewModel" has the below properties
Phone (int)
AgentDetail (string)
then generate formData as follows
formData = {
logType: logType.value, // Parameter to add a new log
logComments: logComments.value, // Parameter to add a new log
agent: agent.value // Parameter to add a new log
vm : { // Parameter to add values to view model
phone : answer.value,
agentDetail : agentDetail.value
}
}
Check this post to know how to render partial views
This post explains https://www.simple-talk.com/dotnet/asp.net/revisiting-partial-view-rendering-in-asp.net-mvc/

In an MVC project, how do you update the model when a drop down list changes value?

I have a MVC project using Kendo controls. On one of the views is a drop down box and text box. Both are initially getting their values from the model. How can I change the model (and therefore the text box) when the user selects an item from the drop down?
For example, the Model is filled in the controller setting the original value of the item the drop down box is based on to "General" and the item the text box is based on to "Widgets". When the user selects "Special" from the drop down, the controller would query the database to get data based on "Special", find that the new value of the text box should say "Doodads", add "Doodads to the model and change the text box to "Doodads".
View
#model GPC.Models.ModelInstrumentListingDetail
#using (Html.BeginForm("InstrumentListingDetailClick", "Home", FormMethod.Post, new { id = "InstrumentListingDetailForm" }))
{
<div id="divInstrumentListingDetailHeader" class="detailDivs">
<table>
<tr>
<tr>
<td style="text-align: right;" class="dropdowns">
<label>Category:</label>
</td>
</tr>
</table>
</div> // divInstrumentListingDetailHeader
<div id="divInstrumentListingDetailBody" class="detailDivs details">
<table class="details">
#*Field 1*#
<tr>
<td style="text-align: right;">
#Html.DisplayFor(m => m.Label1)
</td>
<td width="2px;"> </td>
<td class="dropdowns">
#Html.TextBoxFor(m => m.Field1, new { #class = "details" })
</td>
</tr>
</table>
</div> // divInstrumentListingDetailBody
}
<script>
function onChange_ddInstrumentCategory(arg) {
var categoryID = $(arg).find('option:selected').val();
// Update model based on the category ID
}
</script>
Controller
public ActionResult InstrumentListingEdit(TblInstrumentTag model)
{
TblInstrumentTag currentInstrumentTag = data.GetInstrumentTagByID(model.InstrumentTagID);
// Fill Category drop down
List<TblInstrumentFormCategory> categories = data.GetAllCategories();
// Create model
ModelInstrumentListingDetail detailModel = new ModelInstrumentListingDetail
{
InstrumentTagID = currentInstrumentTag.InstrumentTagID,
InstrumentCategory = categories.FirstOrDefault().InstrumentFormCategoryID,
Field1 = currentInstrumentTag.FormCategory1Value1,
Label1 = categories.FirstOrDefault().Label1 + ":",
ieInstrumentCategories = new SelectList(categories, "InstrumentFormCategoryID", "InstrumentFormCategoryName")
};
return View("InstrumentListingEdit", detailModel);
}
Model
public class ModelInstrumentListingDetail
{
// Drop down ID's
public int InstrumentTagID { get; set; }
public int InstrumentCategory { get; set; }
// Detail fields
public string Field1 { get; set; }
// Detail labels
public string Label1 { get; set; }
// Drop downs for add/edit page
public IEnumerable<SelectListItem> ieInstrumentCategories { get; set; }
}
What I'd like is to get from the javascript to something like this code below to update the text box. I'd rather not post the entire page. I don't want the screen to "blink"; I just want the user to select an item from the dropdown and for the textbox value to change.
Need to get from jQuery to something like this without submitting the form:
public ActionResult UpdateModel(TblInstrumentTag model, int newCatgoryID)
{
TblInstrumentTag currentInstrumentTag = data.GetInstrumentTagByID(model.InstrumentTagID);
// Fill Category drop down
List<TblInstrumentFormCategory> categories = data.GetAllCategories();
// Create model
ModelInstrumentListingDetail detailModel = new ModelInstrumentListingDetail
{
InstrumentTagID = currentInstrumentTag.InstrumentTagID,
InstrumentCategory = categories.FirstOrDefault().InstrumentFormCategoryID,
Field1 = currentInstrumentTag.FormCategory2Value1, // <- Value of Field 1 has changed
Label1 = categories.FirstOrDefault().Label1 + ":",
ieInstrumentCategories = new SelectList(categories, "InstrumentFormCategoryID", "InstrumentFormCategoryName")
};
return View("InstrumentListingEdit", detailModel);
}
JQuery is a good place to start. If I understand correctly, you only want to query the DB after changing the drop down's value, and then changing the value of the textbox to the corresponding change.
JQuery:
$(document).ready(function(){
$('#myDropDown').change(selectionChange());
});
function selectionChange() {
var dropDownValue = $('#myDropDown').val();
var textBox = $('#myTextBox');
$.ajax({
url: "/mycontroller/querydb",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(dropDownValue),
success: function (data, status) {
textBox.val(data);
},
type: "post"
});
return;
}
Controller:
[HttpPost]
public JsonResult QueryDB(string dropDownValue)
{
string newTextBoxValue = string.Empty;
//your db code
return Json (newTextBoxValue) );
}
It's a fairly watered down version of a JQuery AJAX to MVC Controller deal. Hopefully it will work for you!

Categories

Resources