How to pass textbox input value and dropdownlist selected value as input parameters to Controller in mvc4 using jquery? - asp.net-mvc-4

I need to pass textbox input value and dropdownlist selected value to Controller in MVC4 ????????? For Eg : I have a Form with Textbox and Dropdownlist and a ( PartialView For Webgrid) . When i give datetime input to Textbox and Selected the "DoctorName" in Dropdown . Then i need to pass textbox input value and dropdownlist values as parameters to the controller ??????? My Controller is used to bind the webgrid in PartialView... The Code i tried which is not working......#doctortype is dropdownlist,#AppointmentDate is Textbox input datetime.
jquery:
<script type="text/javascript">
$(document).ready(function () {
$('#doctorType').change(function (e) {
e.preventDefault();
var url = '#Url.Action("Filter")';
$.get(url, { doctorname: $(this).val() }, { AppointmentDate: $('#AppointmentDate').val() }, function (result) {
$('#FilterWebgrid').html(result);
});
});
});
</script>

is not
$.get(url, `{ doctorname: $(this).val() }, { AppointmentDate: $('#AppointmentDate').val() }`, function (result) {
$('#FilterWebgrid').html(result);
});
You are sending two object. You have to send a single object like this:
$.get(url, { doctorname: $(this).val(), AppointmentDate: $('#AppointmentDate').val() }, function (result) {
$('#FilterWebgrid').html(result);
});
2) check the console and network tab and check if there is any error.
3) The value you are passing must be the same type as the parameter expected in the Action

This is just simple method to post data. If your controller returns data back to view, try $.getJSon();
<input type="text" value="doctor name" id="txtDoctor"/>
<select id="ddlDoctor"><option>SomeSelectedData</option></select>
<script>
$(document).ready(function() {
var txtValue = $('#txtDoctor').val();
var ddlValue = $('#ddlDoctor').val();
$.ajax({
url: '/controller/action',
data: { doc: txtValue, name: ddlValue },
traditional: true,
success: function(result) {
alert(result.status);
}
});
});
</script>
to know more about getJSon and JSON Result, check these links.
GetJson with parameters
JSON result in view

Related

how to get the text from a text box using formCollection, that gets its value from a dropdown using jquery

I have a textbox which gets its value from a dropdown using jquery. I want that value to be saved in database using formcollection. But I get '0' when I get its value.
here, is the textbox;
<input type="number" name="Total" id="Total" disabled="disabled" style="width: 70px;" />
and here is the ajax code that gets the value from dropdown and shows it in the textbox;
function getValue() {
var value = $("#CityDDL").val();
$.ajax({
url: '/Admin/yourActionMethod',
data: { 'id': value },
type: "post",
cache: false,
success: function (result) {
$('#Total').val(result);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#Total').text("Error encountered while getting total");
}
});
}
Now, im doing this to save that value in database;
am.TotalAmount = Convert.ToInt32(fc["Total"]);
but in debugging mode, it shows 0.

asp.net MVC autocomplete with Html.TextBoxFor

I am modifying a preexisting application. I am trying to add the jquery autocomplete functionality. I have it working and calling the controller but the problem is the name attribute in the input field is "someClass.someMethod" so because I can't put this in the controller parameter like this, but still want to satisfy asp.net's Model Binding rules, what can I do?
Controller:
public JsonResult GetPs(string pN, PSModel pS)
{
List<string> pNs = null;
pNs= pS.PEntryBL.BusinessLayerPS.PS
.Where(x => x.Text.StartsWith(pN)).Select(y => y.Text).ToList();
return Json(pNs, JsonRequestBehavior.AllowGet);
}
View:
$(function () {
$("#autoCompletePNBox").autocomplete({
source: '#Url.Action("GetPs", "PS", new {pS = #Model})'
});
});
In Form:
#Html.Label("Scan PN: ", new { #class = "DFont"})
#Html.TextBoxFor(r => r.PEntryBL.PS, new { #class = "pageFont", id = "autoCompletePNBox" })
Using This Post
I was able to get it working by grabbing the value of the input field and passing it on each function call (or each time a user enters a character).
Now when the user selects the item from the autocomplete list, and selects submit then the frameworks form model binding behind the scenes will still work as originally implemented.
Here is the jquery code change:
<script type="text/javascript">
$(function () {
var src = '#Url.Action("GetPs", "PS", new {pS = #Model})'
$("#autoCompletePNBox").autocomplete({
source: function (request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
pN: $("#autoCompletePNBox").val()
},
success: function (data) {
response(data);
}
});
}
});
});
I couldn't figure this out right away as my Jquery skills are not very strong. Hopefully this helps someone.

BootstrapValidator for bootstrap typeahead

I want to know if BootstrapValidator http://bootstrapvalidator.com/ has a validation for typeahead.
I have a form where where i am validating my fields using the validator. One of the fields is a inout field where a typeahead is attached so the input field is filled by the typeahead select.
But whenever I start typing in the input field the validator validates its true. I want something like it must validates only after typeahead selection and not by writing in the the input field.
$(document).ready(function() {
var options = {};
options.common = {
minChar: 1
};
options.ui = {
showVerdictsInsideProgressBar : true,
viewports : {
progress : ".pwstrength_viewport_progress"
}
};
.......
$('#user_country').on('input', function() {
$(this).parent().find('.small').hide();
});
$('#user_reg_form').bootstrapValidator({
excluded: ':disabled',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
........
country: {
validators: {
notEmpty: {
message: 'city is required'
}
}
},
}
})
My typeahead looks like
$(ele).typeahead({
select:function(){
// here i do the select.....
}
});
I ran into a similar problem using a date picker - you could try manually binding the validation - e.g:
$('#userCountry').on('blur', function(e) {
$('#user_reg_form').bootstrapValidator('revalidateField', 'userCountry');
});
Does your typeahead control limit them to one of the options in the list?

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

Changing Jquery variables

I have some jquery that inputs text into a database and then clears the textarea. However the textarea is not being cleared. Below is the code indicating which line doenst work. When i replace this line with alert(commentbox) I get the value of the comment box so i know that the variable is working. I just don't know how to clear the variable.
Jquery:
<script type='text/javascript'>
$('document').ready(function () {
$('.commentContainer').load('../writecomment.php');
$("form").on("submit", function (e) {
e.preventDefault();
var $form = $(this);
var commentbox = $(this).children('.commentBox').val();
$.ajax({
"url": $form.attr("action"),
"data": $form.serialize(),
"type": $form.attr("method"),
success: function () {
$('.commentContainer').load('../writecomment.php');
commentbox = ""; //this line doesnt work
}
});
});
});
I should also mention that when i replace the bad line with $('.commentBox').val(''); the values clear. the problem is that it clears all the textareas, not just the one that i use .children() to find.
</script>
var commentboxElem = $(this).children('.commentBox');
and in your success:
commentboxElem.val('');
var $form = $(this);
var commentboxObj = $(this).children('.commentBox');
var commentBoxVal=commentboxObj.val();
$.ajax({
"url": $form.attr("action"),
"data": $form.serialize(),
"type": $form.attr("method"),
success: function () {
$('.commentContainer').load('../writecomment.php');
commentboxObj.val(""); //this will work
}
});
with commentbox="", you were trying to update the content of a javascript variable, not the actual textbox.