I am a beginer ...I don't know how to use dropdown in MVC this....I have used it like this
In ItemMaster.cshtml
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList)
In Controller.cs
public ActionResult ItemMaster(Item model)
{
ObservableCollection<Item> ItemList = new ObservableCollection<Item>();
Item Item = new Models.Item();
ItemList = Item.GetItemList();
Item Product = new Item();
DataTable dtProduct = new DataTable();
dtProduct = Item.GetProductList();
IList<Item> MyList = new List<Item>();
foreach (DataRow mydataRow in dtProduct.Rows)
{
MyList.Add(new Item()
{
Id = Convert.ToInt32(mydataRow["Id"].ToString().Trim()),
Product_Name = mydataRow["Name"].ToString().Trim()
});
}
var ProductName = new SelectList(MyList, "Id", "Product_Name");
ViewData["ProductName"] = ProductName;
return View(ItemList);
}
I am using Item list to fill grid view.... And I am using view data to fill drop down list....It is working fine.... I don't know how to get selected value when Button is clicked.
Try this,
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList)
<input type="button" id="btnasd" value="Click"/>
Script
<script type="text/javascript">
$(document).ready(function () {
$("#btnasd").click(function () {
var Id = $("#ProductName").val();
$.ajax({
url: '#Url.Action("Action", "Controller")',
type: "Post",
data: { ProductNameId: Id },
success: function (result) {
$("#mygrid").html('');
$("#mygrid").append(result.Data);
}
});
});
});
</script>
Do following(for onchange event of DropDownList):
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList,
"-Select Product-", new { onchange = "doFunction();" })
javascript:
<script type="text/javascript">
$(document).ready(function () {
doFunction();
});
function doFunction() {
var PassVal = $("#ProductName").val(); //It has dropdownlist's selected value.
if (PassVal != '') {
//Do Ajax operations to load data in GridView(On Same Page).
$.ajax({
url: '<CONTROLLER/ACTIONANME>', //Specify Actionname in controller from which you will get data.
type: "POST",
data: {
ProductName: PassVal
},
dataType: "html",
success: function (data) {
$("#GridView").empty(data); //empty gridview
$("#GridView").html(data); //Load data to gridview
},
error: function () {
alert("No Records Found");
}
});
}
}
</script>
Or On button click
#Html.DropDownList("ProductName", ViewData["ProductName"] as SelectList,
"-Select Product-")
<input type="button" id="btnSubmit" value="Submit"/>
script:
$('#btnSubmit').click(function(){
var PassVal = $("#ProductName").val(); //It has dropdownlist's selected value.
if (PassVal != '') {
//Do Ajax operations to load data in GridView(On Same Page).
$.ajax({
url: '<CONTROLLER/ACTIONANME>', //Specify Actionname in controller from which you will get data.
type: "POST",
data: {
ProductName: PassVal
},
dataType: "html",
success: function (data) {
$("#GridView").empty(data); //empty gridview
$("#GridView").html(data); //Load data to gridview
},
error: function () {
alert("No Records Found");
}
});
}
});
Ask me if you have any query.
Note: You can also use DropDownListFor for model binded dropdown.
Related
I have a view in ASP.NET MVC application, with a dropdownlist and other text fields. The dropdownlist is populated with file names from a specific directory. So, on selection of a specific file name from the dropdownlist, I want to populate other text fields with contents on the selected file. The reading of the file is already taken care of.
I'm struggling with filling in the text fields after file name selection from the dropdownlist.
How can I do this?
<div class="col-lg-4">
#Html.DropDownList("cardProgram", null, "--Select--", new { #class = "form-control input-group-lg" })
</div>
Ajax code:
$(document).ready(function () {
$("#FileDDL_ID").change(function () {
var file = $('#FileDDL_ID option:selected').text();
$.ajax({
url: "#Url.Action("YourAction", "Controller")",
type: "POST",
dataType: "json",
data: { filename: file }, //pass file as parameter to controller
async: false,
error: function () {
},
//assuming your data property is called fileDetail1
success: function (data) {
if (Object.keys(data).length > 0) {
$('#fileDetailtxtBox1').val(data[0].fileDetail1);
$('#fileDetailtxtBox2').val(data[0].fileDetail2);
}
}
});
});
});
Controller code:
[HttpPost]
public JsonResult YourAction(string filename)
{
using (var db = new DataContext())
{
//use filename as condition
var details = db.YourDbset.Condition.ToList();
return Json(details, JsonRequestBehavior.AllowGet);
}
}
Hope this is clear, I have tried to name variables as per your question. So basically, you are passing the selected value from the dropdown to the Controller action and getting back related data and populating fields with jQuery Ajax.
I finally got it working. See below :
html code:
#Html.LabelFor(m => m.cardProgram, new { #class = "col-lg-2" })
<div class="col-lg-4">
#Html.DropDownListFor(m => m.cardProgram, null, "--Select Card Profile--", new
{
#class = "col-lg-4 form-control input-group-lg",
#onchange = "BindProfile()"
})
</div>
ajax code:
<script>
function BindProfile() {
var selectedProfile = $('#cardProgram').val();
$.ajax({
url: '/CardCreation/BindProfile',
type: "GET",
dataType: "JSON",
data: { cardProgram: selectedProfile },
success: function (profile) {
$("#sBin").val(profile.card.bin)
$("#IsChip").val(profile.card.chip)
$("#IsBatches").val(profile.output.splitBatches)
$("#BatchSize").val(profile.output.batchSize)
$("#SplitPostcard").val(profile.output.splitPostcardFile)
$("#SubCat").val(profile.batchDetails.subcategory)
$("#UserCodeIncrement").val(profile.batchDetails.usercodeIncrement)
$("#ExpiryDate").val(profile.batchDetails.expiryWindowMM)
$("#Bureau").val(profile.chipDetails.bureau)
$("#BatchType").val(profile.chipDetails.batchType)
$("#EffectiveDate").val(profile.chipDetails.effectiveDateOffsetMM)
$("#ServiceCode").val(profile.emvApplications[0].serviceRestrictionCode)
}
});
}
</script>
Controller code:
public async Task<ActionResult> BindProfile(string cardProgram)
{
var profile = new Profile();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:59066/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ViewBag.country = "";
HttpResponseMessage response = await client.GetAsync(client.BaseAddress + "api/CardCreation/GetSelectedCardProfile?selectedProfile=" + cardProgram);
if (response.IsSuccessStatusCode)
{
//profile = response.Content.ReadAsAsync<Profile>().Result;
profile = JsonConvert.DeserializeObject<Profile>(response.Content.ReadAsStringAsync().Result);
return Json(profile, JsonRequestBehavior.AllowGet);
}
else
{
return Json(profile, JsonRequestBehavior.AllowGet); ;
}
}
}
I've coded for multiple values that resides inside listbox on button click. I have used autocomplete textbox to get the required value along with its id. Then i managed to add those values inside the listbox. Now what i want is to pass id's against those values in listbox instead of names. Below is my code that I'm running.
StudentBatch.cs
public string studentId { get; set; }
public string StudentName { get; set; }
public List<string> selectedids { get; set; }
public List<string> names { get; set; }
public List<string> SelectedNames { get; set; }
Create.cshtml
#using (Html.BeginForm("Create", "Student", FormMethod.Post))
{
<div class="form-group">
<div class="col-md-12">
#Html.EditorFor(model => model.StudentName, new { id = "StudentName" })
<input type="button" value="Add Text" id="addtypevalue" />
<div id="typevaluelist"></div>
</div>
</div>
<div id="new" style="display:none;">
<div class="typevalue">
<input type="text" name="typevalue" />
<button type="button" class="delete">Delete</button>
</div>
</div>
<div id="hiddensq">
</div>
for (int i = 0; i < Model.names.Count; i++)
{
#Html.Hidden("UserValues", Model.names[i]);
}
#Html.ListBoxFor(m => m.SelectedNames, new SelectList(Model.names))
<div id="partialDiv">
#{
Html.RenderPartial("GetListBox", Model);
}
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$("#StudentName").autocomplete({
//autocomplete: {
// delay: 0,
// minLength: 1,
source: function (request, response)
{
$.ajax({
url: "/Student/CreateStudent",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function(data) {
try {
response($.map(data,
function (item)
{
return { label: item.FirstName, id: item.Id };
}));
} catch (err) {
}
}
});
},
messages:
{
noResults: "jhh", results: "jhjh"
}
});
});
</script>
<script>
$(function () {
$('#addtypevalue').click(function (e) {
var name = $("#StudentName").val();
alert(name);
$('#SelectedNames').
append($("<option></option>").
attr("value", name).
text(name));
$('#hiddensq').append("<input name='UserValues' type='hidden' value='"+ name +"'/>");
});
});
</script>
StudentController.cs
public ActionResult Create()
{
Context.Student student = new Context.Student();
Models.StudentBatch studBatch = new Models.StudentBatch();
studBatch.names = new List<string>();
studBatch.names.Add("Add Student Names");
studBatch.BatchNumberList = student.getBatchList();
return View(studBatch);
}
[HttpPost]
public JsonResult CreateStudent(string Prefix)
{
CreateUser user = new CreateUser();
string stdid = "f14570f0-e7a1-4c22-bf69-60ffbeb7e432";
var StudentList1 = user.GetAllUsers().ToList().Where(u => u.FirstName.Contains(Prefix) && u.usertypeid == stdid);
var StudentList = user.GetAllUsers().ToList();
var searchlist = (from student in StudentList1
where student.FirstName.Contains(Prefix)
select student).ToList();
return Json(StudentList1, JsonRequestBehavior.AllowGet);
}
// POST: Student/Create
[HttpPost]
public ActionResult Create(Models.StudentBatch student, IEnumerable<string> UserValues)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
If I understood correctly the problem here is passing multiple IDs from a listbox to a POST? One possible way is to assign viewbag like thus in your controller:
ViewBag.StudentList = new SelectList(db.StudentBatch, "studentId", "StudentName");
I use entities to access my models, I think you have a little bit different approach but the point is to give a collection to the Selectlist. Then you specify the data value field and the data text field.
Then in your view, note that it's not ListBoxFor, as it's dynamic:
#Html.ListBox("StudentList", null)
Then finally to be able to receive the values in the POST add the following parameter to your action and you should be able to iterate through it:
string[] StudentList
Finally managed to get the related from the listbox. I followed the instruction mentioned in a particular question. That's how i did.
$("#StudentName").autocomplete({
source: function (request, response) {
$.ajax({
cache: false,
// async: false, NEVER do this
url: '#Url.Action("CreateStudent", "Student")', // don't hard code your url's
data: { Prefix: request.term }, // change
dataType: "json",
type: "POST",
// contentType: "application/json; charset=utf-8", delete
success: function (data) {
response($.map(data, function (item) {
return {
label: item.label,
id: item.id
}
}));
}
})
},select: function(event, ui) {
$.ajax({
cache: false,
type: "POST",
url: '#Url.Action("GetDetails", "Student")',
data: { id: ui.item.id },
success: function (data) {
var name = $("#StudentName").val();
$('#SelectedNames').
append($("<option></option>").
attr("value", ui.item.id).
text(name));
$('#hiddensq').append("<input name='UserValues' type='hidden' value='" + ui.item.id + "'/>");
}
});
}
});
</script>
and in the controller class
[HttpPost]
public JsonResult GetDetails(string id)
{
ViewBag.Value = id;
return Json(ViewBag.Value, JsonRequestBehavior.AllowGet);
}
I've created a jQuery Accordion using Asp.Net MVC, and it's working fine. The accordion displays a list of employee names, and when I click on an item, it shows the details. I'd like to send an AJAX request to get the employee details when they click on an item, instead of loading all the employee details at once. Please look at my code below.
Also, please tell me how to keep the first item in the accordion collapsed instead of showing the details, and is there any way to move the heading a bit to the right without using  ?
<div id="accordion">
#foreach (var item in Model.Employees)
{
<h3> #item.EmployeeName</h3>
<div id = "accordiondiv">
<p>Address: #item.Address</p>
<p>Town: #item.Town</p>
<p>Postcode: #item.PostCode</p>
<p>PhoneNumber: #item.PhoneNumber</p>
</div>
}
</div>
<script>
$(function () {
$("Accordion").click(function (evt) {
$.ajax({
url: "/Accordion/GetEmployeeDetails",
type: 'POST',
data:
//need code to pass the employeeid that was clicked on the accordion,
success: function (data) {
$.each(data, function (i, val) {
//need code to populate the respective accordion with the employee details
});
}
});
}
});
</script>
Here's a sample to send an AJAX request to the controller:
<div id="accordion">
#foreach (var item in Model.Employees)
{
<h3> #item.EmployeeName</h3>
<div id = "accordiondiv" data-id="#item.EmployeeId">
<p>Address: #item.Address</p>
<p>Town: #item.Town</p>
<p>Postcode: #item.PostCode</p>
<p>PhoneNumber: #item.PhoneNumber</p>
<p><input type="button" id="Accordion" class="btn" name="Accordion" /></p>
</div>
}
</div>
<script>
$(function () {
$(".btn").each(function (){
var button = $(this);
var parentDiv = button.parent();
var employeeId = parentDiv.attr("data-id");
button.click(function (){
$.ajax({
url: "/Accordion/GetEmployeeDetails",
type: 'POST',
data: { employeeId : employeeId},
success: function (data) {
$.each(data, function (i, val) {
//need code to populate the respective accordion with the employee details
});
}
});
});
});
</script>
And in your controller:
[HttpGet]
public ActionResult GetEmployeeDetails(int employeeId)
{
// code: get the details based on employeeId
var detail = new Model.EmployeeDetail();
return Json(detail, JsonRequestBehavior.AllowGet);
}
Thiago's implementation seems like it should work. However, I would create a partial view _EmployeeDetails with how you want the details to look, based on the Employee model,
#model Employee
<p>Address: #item.Address</p>
<p>Town: #item.Town</p>
<p>Postcode: #item.PostCode</p>
<p>PhoneNumber: #item.PhoneNumber</p>
In your controller you'll return it as such,
public ActionResult GetEmployeeDetails(int employeeId)
{
...
var employee = Repository.GetEmployee(employeeId);
return PartialView("_EmployeeDetails", employee);
}
Which result you can use to the set the content of each <div id="accordionDiv"> on the AJAX response,
<script>
$(function () {
$(".btn").each(function (){
var button = $(this);
var parentDiv = button.parent();
var employeeId = parentDiv.attr("data-id");
button.click(function (){
$.ajax({
url: #Url.Action("GetEmployeeDetails"),
type: 'POST',
data: { employeeId : employeeId },
success: function (data) { parentDiv.html(data); }
});
});
});
</script>
I am trying to call an action from jQuery. The action should return true or false,
and based on the return value I will do something.
I have the following code.
$("#payment").click(function (e) {
if($("#deliverytime").attr("disabled")){
//something here...
}
else
{
var postcode=$('#Postcode').val();
var restId='<%:ViewBag.RestaurantId %>';
var URL = "/Restaurant/DoesRestaurantDeliver?restid="+restId+"&&postcode="+postcode;
$.ajax({
type: "GET",
url: URL
}).done(function(msg) {
if(msg==true){
$('#commonMessage').html(msg);
$('#commonMessage').delay(400).slideDown(400).delay(4000).slideUp(400);
return false;
}
else{
$('#commonMessage').html(msg);
$('#commonMessage').delay(400).slideDown(400).delay(4000).slideUp(400);
return false;
}
});
}
});
The code is not working. It says 'msg' is not defined. Is this not the way I should do this using jQuery-ajax? What am I doing wrong?
EDIT:
Controller action
public JsonResult DoesRestaurantDeliver(Int32 restid, string postcode)
{
if (rest.getDeliveryPriceForPostcode(restid, postcode) == null)
{
return Json(Boolean.FalseString, JsonRequestBehavior.AllowGet);
}
else
return Json(Boolean.TrueString, JsonRequestBehavior.AllowGet);
}
Modified function
var postcode = $('#DeliveryInfo_Postcode').val();
var restId = '<%:ViewBag.RestaurantId %>';
var URL = "/Restaurant/DoesRestaurantDeliver?restid=" + restId + "&&postcode=" + postcode;
$.ajax({
url: URL,
dataType: "json",
type: "GET",
data: "{}",
success: function (data) {
if (!data.hasError) {
$('#commonMessage').html(data);
return false;
}
}
});
EDIT -2
<script>
$(document).ready(function () {
$("#checkout").click(function (e) {
getDeliveryInfo();
});
});
function getDeliveryInfo() {
var URL ="/Restaurant/DoesRestaurantDeliver/6/2259"
$.get(URL, function (data) {
alert(data.isValid);
});
}
</script>
<%using (Html.BeginForm())
{ %>
<input type="submit" name="submit" id="checkout"/>
<%} %>
The above code does not work. But If i put the 'checkout' button out side of the form like below, it works.
<%using (Html.BeginForm())
{ %>
<%} %>
<input type="submit" name="submit" id="checkout"/>
You can configure your ajax call like below.
I feel your ajax call having problems on .done(function(msg) {} area.
Try to set success: function (data) {} like below.
<script type="text/javascript">
$(function () {
var companyName = $("#companyname");
$.ajax({
url: "/Company/GetName",
dataType: "json",
type: "GET",
data: "{}",
success: function (data) {
if (!data.hasError) {
companyName.html(data.companyName);
}
}
});
});
</script>
EDIT
Action method should looks like below (This is a sample.Adjust it according to your situation)
[HttpGet]
public JsonResult GetName(string term)
{
var result = Repository.GetName(term);
return Json(result, JsonRequestBehavior.AllowGet);
}
EDIT 2
I would use Anonymous object (isValid) (remember that JSON is a key/value pairs):
Action Method
[HttpGet]
public JsonResult DoesRestaurantDeliver(Int32 restid, string postcode)
{
if (rest.getDeliveryPriceForPostcode(restid, postcode) == null)
{
return Json(new { isValid = false},JsonRequestBehavior.AllowGet);
}
else
return Json(new { isValid = true },JsonRequestBehavior.AllowGet);
}
And then inside the ajax method:
success: function(data) {
if (data.isValid) {
...
}
}
EDIT 3
Just change your button type as below.(since you're not sending any values from form)
<input type="button" name="submit" id="checkout"/>
post methot:
function PostChartValues(meter_id, range_type_id, start_date, end_date) {
var values = $("#type_selection").val();
//values = expected values as string array
$.ajax({
url: '/Widget/GetMeterReadingsTimeSeries',
type: 'POST',
data: { MeterType: meter_id, DateRangeType: range_type_id, StartDate: start_date, EndDate: end_date, Parameters: values },
beforeSend: function () {
$("#chart_loading_div").show();
},
complete: function () {
$("#chart_loading_div").fadeOut();
$(".grids").jqGrid('GridUnload');
grid(meter_id, range_type_id, $("#start_date").val(), $("#end_date").val());
},
success: function (result) {
$("#chart").html(result);
},
error: function (result) {
alert("Seçilen kritere uygun veri bulunamadı!");
}
}); //end ajax
} //end PostChartValues
action method:
public ActionResult GetMeterReadingsTimeSeries(int MeterType, int DateRangeType, DateTime? StartDate, DateTime? EndDate,string[] Parameters)
{
// ...
return PartialView("_TimeSeries", chart);
}
I debugged it. only Parameters array is null. Is there an other way to post array with jquery post?
Thanks.
You can post selected values as string then you parse it back to array. I have created basic sample below,
Markup
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#someButton').click(function () {
var selectedValues = [];
$('#MyDiv input:checked').each(function () {
selectedValues.push($(this).val());
});
console.log(selectedValues);
$.ajax({
url: 'someurl',
type: 'POST',
data: { values: selectedValues.join(",") }
});
});
});
</script>
<button id="someButton">Do Ajax</button>
<div id="MyDiv">
<input type="checkbox" value="test1" />
<input type="checkbox" value="test2" />
<input type="checkbox" value="test3" />
</div>
Controller
public class HomeController : Controller
{
public void Test(string values)
{
string[] selectedValues = values.Split(',');
}
}
An alternate way to get the selected values if you're using Underscore:
var selectedValues = _.map($("#myDiv:checked"), function (item) { return $(item).val(); });