How to bind dropdown value in mvc - javascript

I'm unable to bind the dropdown value. Maybe I'm missing something in my code. Here I'm attaching my view code.
<tr>
<td>
<div class="form-group" style="margin-bottom:0px;">
#Html.DropDownList("ProofId", ViewBag.Idproofs as SelectList, new { #class = "form-control", id = "ProofType2", name = "ProofType2" })
</div>
</td>
<td>
<div class="form-group" style="margin-bottom:0px;">
#Html.TextBoxFor(x => x.EvidenceData[1].ProofNumber, new { #class = "form-control", id = "IdNumber2", name = "IdNumber2" })
</div>
</td>
<td>
<div class="form-group" style="margin-bottom:0px;">
#Html.TextBoxFor(x => x.EvidenceData[1].ProofImage, new { #class = "form-control", id = "ProofPic2", type = "file", name = "ProofPic2" })
<i class="fa fa-download" aria-hidden="true"></i> Download Image
</div>
</td>
</tr>
And this is my controller code:
public ActionResult EditProfile(string country)
{
if (!User.Identity.IsAuthenticated)
return new RedirectResult(Utility.Config("RedirectPath"));
var idprooflist = AccountManager.LoadProoftypes(country ?? "United States");
ViewBag.Idproofs = new SelectList(idprooflist, "ProofId", "ProofName");
UserRegistration UserProfileData = ProviderManagerBLL.GetProviderDetails(Convert.ToInt32(Session["UserID"].ToString()));
return View(UserProfileData);
}

The below should work for you:
<div class="form-group" style="margin-bottom:0px;">
#Html.DropDownList("ProofId", (SelectList)ViewBag.Idproofs, new { #class = "form-control", id = "ProofType2", name = "ProofType2" })
</div>
You are using a ViewBag to pass your values to the View and all you have to do is reference what you want from it. What you were doing before wouldn't work

Related

Creating an array from table data and currently getting empty strings in the array

I have a table where the owner is meant to enter details:
<table id="ownerDetailsTable" style="margin-top: 20px; margin-bottom: 20px; width: 100%">
<thead>
<tr>
<td style="font-weight: bold">HP Point of Contact Name</td>
<td style="font-weight: bold">HP Point of Contact Title</td>
<td style="font-weight: bold">HP Point of contact email</td>
</tr>
</thead>
<tbody id="tableToModify">
<tr id="1">
<td>
#Html.TextBoxFor(m => m.InterventionOwnerName, new { #class = "form-control element-one", #maxlength = 250, placeholder = "Owner Name", value = "" })
</td>
<td>
#Html.TextBoxFor(m => m.InterverntionOwnerTitle, new { #class = "form-control element-two", #maxlength = 250, placeholder = "Owner Title", value = "" })
</td>
<td>
#Html.TextBoxFor(m => m.InterventionOwnerEmail, new { #class = "form-control element-three", #maxlength = 250, placeholder = "Owner Email", value = "" })
</td>
</tr>
</tbody>
</table>
<input id="addRow" , type="button" onclick="createRow(); getOwnerDetails()" value="Add Point of Contact" class="btn btn-primary" />
Currently, on click, a new row of inputs is created and the details entered by the user are meant to go into an array:
<script>
var ownerDetailArray = [];
function getOwnerDetails() {
$('table#ownerDetailsTable tr').each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('input');
if (tableData.length > 0) {
tableData.each(function () {
arrayOfThisRow.push($(this).text())
});
ownerDetailArray.push(arrayOfThisRow);
}
console.log(ownerDetailArray);
});
}
The array is being created but the strings in the array - which should be the info entered by the user - are empty. I feel as though the issue in the way that I am attempting to find the data and push it into the array. Any help/advice would be much appreciated!
If you are trying to get input value , then change arrayOfThisRow.push($(this).text()) to arrayOfThisRow.push($(this).val());
I assume your #Html.TextBoxFor creates <input /> tag.
var ownerDetailArray = [];
function getOwnerDetails() {
$('table#ownerDetailsTable tr').each(function () {
var arrayOfThisRow = [];
var tableData = $(this).find('input');
if (tableData.length > 0) {
tableData.each(function () {
arrayOfThisRow.push($(this).val());
});
ownerDetailArray.push(arrayOfThisRow);
}
console.log(ownerDetailArray);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="ownerDetailsTable" style="margin-top: 20px; margin-bottom: 20px; width: 100%">
<thead>
<tr>
<td style="font-weight: bold">HP Point of Contact Name</td>
<td style="font-weight: bold">HP Point of Contact Title</td>
<td style="font-weight: bold">HP Point of contact email</td>
</tr>
</thead>
<tbody id="tableToModify">
<tr id="1">
<td>
<input class = "form-control element-one", maxlength="250", placeholder = "Owner Name", value = ""/>
<#Html.TextBoxFor(m => m.InterventionOwnerName, new { #>class = "form-control element-one", #maxlength = 250, placeholder = "Owner Name", value = "" })
</td>
<td>
<input class = "form-control element-one", maxlength="250", placeholder = "Owner Name", value = ""/>
#Html.TextBoxFor(m => m.InterverntionOwnerTitle, new { #class = "form-control element-two", #maxlength = 250, placeholder = "Owner Title", value = "" })
</td>
<td>
<input class = "form-control element-one", maxlength="250", placeholder = "Owner Name", value = ""/>
#Html.TextBoxFor(m => m.InterventionOwnerEmail, new { #class = "form-control element-three", #maxlength = 250, placeholder = "Owner Email", value = "" })
</td>
</tr>
</tbody>
</table>
<input id="addRow" , type="button" onclick="getOwnerDetails()" value="Add Point of Contact" class="btn btn-primary" />

how to add multiple of model in one view

I want to add my class model in my index view because I need ClassID for dropdown to show classes in my view but don't know how to.
This is my index:
#using opr.Models;
#using PagedList;
#using PagedList.Mvc;
#model PagedList.IPagedList<opr.Data.C_QuestionTable>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div class="alert-success form-control m-auto w-75 custom-form">
<div class="col-6 pb-3 input-control">
<label for="ex3"> Select Class:</label>
#Html.DropDownListFor(model => model.ClassID, (SelectList)ViewBag.dataForDropDowns, new { #class = "form-control select2ddl" })
</div>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
QuestionText
</th>
</tr>
#foreach (var item in Model)
{
foreach (var answer in item.C_AnswerTable)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.QuestionText)
#Html.RadioButton("searchBy", answer.Options, true)
<text>#answer.Options</text>
</td>
</tr>
}
}
<tr>
<div class="pagination pull-left">
<hr />
<td colspan="3">#Html.PagedListPager(Model, page => Url.Action("Index", new { page = page }))</td>
</div>
</tr>
</table>
</div>
This is my Controller:
examsEntities db = new examsEntities();
public ActionResult Index(int?page)
{
var mod1 = db.myclasses.Select(s => new { s.ID, s.C_name }).ToList();
SelectList sList = new SelectList(mod1, "ID", "C_name");
ViewBag.dataForDropDown = sList;
var pageNumber = page ?? 1;
var pageSize = 3;
var question = db.C_QuestionTable.OrderBy(x => x.QuestionText).ToPagedList(pageNumber, pageSize);
return View(question);
}
namespace OMS.Models
{
public class AbcModel
{
public int Id { get; set; }
public string Name{ get; set; }
public Classmodel classmodel{ get; set; }
}
}
bind class model into Index model(Abc model) and now in view
#using opr.Models;
#using PagedList;
#using PagedList.Mvc;
#model PagedList.IPagedList<opr.Data.C_QuestionTable>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div class="alert-success form-control m-auto w-75 custom-form">
<div class="col-6 pb-3 input-control">
<label for="ex3"> Select Class:</label>
#Html.DropDownListFor(model => model.classmodel.ClassID,
(SelectList)ViewBag.dataForDropDowns, new { #class = "form-control
select2ddl" })
</div>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
QuestionText
</th>
</tr>
#foreach (var item in Model)
{
foreach (var answer in item.C_AnswerTable)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.QuestionText)
#Html.RadioButton("searchBy", answer.Options, true)
<text>#answer.Options</text>
</td>
</tr>
}
}
<tr>
<div class="pagination pull-left">
<hr />
<td colspan="3">#Html.PagedListPager(Model, page => Url.Action("Index", new { page = page }))</td>
</div>
</tr>
</table>
</div>
Hope it will help you

Pass parameters to actionresult from jsonresult

I wrote code to filter results like following image ,
once after it filter I want to send model values of following field as parameters to another controller method, I can call that method once I click Generate Report button
this is view file
#model project_name.Models.SearchVM
....
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
....
<div class="row">
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Type, Model.TypeList, "Select the type", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Type, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
...............
<div class="row">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Generate Report" class="btn btn-success submit" onclick="location.href='#Url.Action("ReportExport", "Home", new { type = Model.Type , ............. })'" /> <button id="search" type="button" class="btn btn-success submit">Search</button>
</div>
</div>
</div>
}
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Product name</th>
<th>Type</th>
.........
<th>Action</th>
</tr>
</thead>
<tbody id="table"></tbody>
</table>
<table id="template" class="table" style="display: none;">
<tr>
<td></td>
<td></td>
<td></td>
........
<td><a>Edit</a></td>
</tr>
</table>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
<script type="text/javascript">
$(function () {
$('.datepicker').datepicker({
dateFormat: 'yy/mm/dd', changeMonth: true,
changeYear: true, yearRange: '1910:2015'
});
});
</script>
<script type="text/javascript">
var url = '#Url.Action("FetchProducts")';
var editUrl = '#Url.Action("Edit")';
var type = $('#Type');
..............
var template = $('#template');
var table = $('#table');
$('#search').click(function () {
table.empty();
$.getJSON(url, { type: type.val(), ......, function (data) {
$.each(data, function (index, item) {
var clone = template.clone();
var cells = clone.find('td');
cells.eq(0).text(item.ID);
cells.eq(1).text(item.Name);
cells.eq(2).text(item.Type);
........................
cells.eq(7).text(item.Status);
var href = '#Url.Action("Edit")' + '/' + item.ID;
cells.eq(8).children('a').attr('href', href);
table.append(clone.find('tr'));
});
});
});
</script>
}
I want to call and send parameters to ReportExport method once I click Generate Report button
But I'm getting null values , I think this is because of I'm doing searching using Json , So How can I get Type value and send that as parameter ,
[HttpGet]
public ActionResult ReportExport(string id, string type, ...........)
{
#Url.Action()
is razor code. It's evaluated on the server before it's sent to the view. So you have to build your URL like quoted above.
var url = $(this).data('baseurl') + '?type=' + $('#Type').val() + '&category=' + $('#Category').val() + ...;
Your 'Generate Report' button includes #Url.Action("ReportExport", "Home", new { type = Model.Type, ... which is razor code. Razor code is parsed on the server before its sent to the view so its generating the route values based on the initial values of your model, not the edited values.
You can use jQuery to build you url based on the form controls.
Html
<input type="button" id="report" data-baseurl="#Url.Action("ReportExport", "Home")" value="Generate Report" class="..." />
Script
$('#report').click(function() {
// build the url
var url = $(this).data('baseurl') + '?type=' + $('#Type').val() + '&category=' + $('#Category').val() + ......;
// redirect
location.href = url;
});

Is possible to create htmlhelpers dynamically?

I wanted to create a htmlhelpers elements depending on the value of dropdown list. Here is the code:
Dropdown
<select id="pracownicy">
<option value="biurowy" style="color: black">Pracownik biurowy</option>
<option value="przewodnik" style="color: black">Przewodnik</option>
</select>
and script be like:
<script>
function pracownicy() {
var x = document.getElementById("pracownicy");
if (x.value.equalTo("biurowy"))
{
}
if (x.value.equalTo("przewodnik")) {
}
}
</script>
Inside these script i would like to create dynamically something like this:
For biurowy value:
<div class="form-group">
#Html.LabelFor(model => model.Pracownik_biurowy.Nazwa_uzytkownika, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Pracownik_biurowy.Nazwa_uzytkownika, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Pracownik_biurowy, "", new { #class = "text-danger" })
</div>
</div>
And for przewodnik value:
<div class="form-group">
#Html.LabelFor(model => model.Przewodnik.Uprawnienia, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Przewodnik.Uprawnienia, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Przewodnik.Uprawnienia, "", new { #class = "text-danger" })
</div>
</div>
How to do this ?
Here is a working example
function handleChange(){
var strg="";
$( "select option:selected" ).each(function(){
strg = strg + this.value;
});
if (strg =="biurowy"){
alert('adding1');
$('#cont').append('<p>yourForm1</p>');
}
if (strg =="przewodnik"){
alert('adding2');
$('#cont').append('<p>yourForm2</p>');
}
}
$('#pracownicy').change(handleChange);
You need to replace <p>yourFormX</p> with your form code.
Pay attention that I changed dropdown code slightly as follows:
<select id="pracownicy">
<option value="unselected" style="color: black">Not Selected</option>
<option value="biurowy" style="color: black">Pracownik biurowy</option>
<option value="przewodnik" style="color: black">Przewodnik</option>
</select>

Filter kendo dropdownlist to remove options

I want to filter security questions such that if I select questiona from the list of questions, for the next questions, I no longer see questiona in the list of security questions. This is to prevent duplicate selection of security questions.
Here's a jsfiddle with a pure jquery implementation:
http://jsfiddle.net/jbfbxvoo/
I was wondering how I can use the same approach to filter kendo dropdownlists:
E.g. I have three dropdownlists like:
<table style="float: left; width:300px;">
<tr>
<td>
<div class="editor-field">
#(Html.Kendo().DropDownListFor(m => m.Q1Id).HtmlAttributes(
new { style = "width:250px;", #id = "idQuestion1", #class="security"})
.Name("Q1DropDown")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Controllers.AccountController.SecurityQuestionList())
.Enable(true)
.Events(e=>e.Change("CreateAccount.QuestionChanged")))
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-field">
#Html.TextBoxFor(model => model.A1, new { #class = "formTextbox k-textbox", #id = "idAnswer1" })
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-field">
#(Html.Kendo().DropDownListFor(m => m.Q2Id).HtmlAttributes(
new { style = "width:250px;", #id = "idQuestion2", #class="security" })
.Name("Q2DropDown")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Controllers.AccountController.SecurityQuestionList())
.Enable(true)
.Events(e=>e.Change("CreateAccount.QuestionChanged")))
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-field">
#Html.TextBoxFor(model => model.A2, new { #class = "formTextbox k-textbox", #id = "idAnswer2" })
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-field">
#(Html.Kendo().DropDownListFor(m => m.Q3Id).HtmlAttributes(
new { style = "width:250px;", #id = "idQuestion3", #class="security" })
.Name("Q3DropDown")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(Controllers.AccountController.SecurityQuestionList())
.Enable(true)
.Events(e=>e.Change("CreateAccount.QuestionChanged")))
</div>
</td>
</tr>
<tr>
<td>
<div class="editor-field">
#Html.TextBoxFor(model => model.A3, new { #class = "formTextbox k-textbox", #id = "idAnswer3" })
</div>
</td>
</tr>
</table>
I tried this but doesn't work:
QuestionChanged: function () {
var sec = $('.security');
sec.change(function () {
sec.find('option').show().end().each(function () {
$('option[value="' + $(this).val() + '"]:not(:selected):not([value="0"])', sec).hide();
});
}).change();
}
For this implementation i have an idea, where first you need to have 3 dropdownlist that have one same datasource/observable but three different value to store each dropdownlist value and point to one same change event, example in mvvm
<h4 class="title">DropDownList</h4>
<input class="customdropdownlist" data-role="dropdownlist" data-text-field="text" data-value-field="value" data-bind="source:dataSource, value:dd1, events:{change:onChange}" style="width: 400px;"/>
<h4 class="title">DropDownList</h4>
<input class="customdropdownlist" data-role="dropdownlist" data-text-field="text" data-value-field="value" data-bind="source:dataSource, value:dd2, events:{change:onChange}" style="width: 400px;"/>
<h4 class="title">DropDownList</h4>
<input class="customdropdownlist" data-role="dropdownlist" data-text-field="text" data-value-field="value" data-bind="source:dataSource, value:dd3, events:{change:onChange}" style="width: 400px;"/>
On the view model change event you do your logic, maybe you can write better code than mine right now but the main point is
To loop through all 3 dropdownlist <li></li> , and compare with the
three value dd1,dd2,dd3 hide if match, otherwise show it
And the code :
var dropdowns = $("input.customdropdownlist");
for(j=0;j<dropdowns.length;j++){
var list = $(dropdowns[j]).data("kendoDropDownList").ul.find("li.k-item");
for(i=0;i<list.length;i++){
if(viewModel.dd1 &&list[i].textContent == viewModel.dataSource.get(viewModel.dd1).text){
$(list[i]).hide();
}else if(viewModel.dd2 &&list[i].textContent == viewModel.dataSource.get(viewModel.dd2).text){
$(list[i]).hide();
}else if(viewModel.dd3 &&list[i].textContent == viewModel.dataSource.get(viewModel.dd3).text){
$(list[i]).hide();
}else{
$(list[i]).show();
}
}
}
Working example in kendo dojo, add
updated dojo from modifying your code.
I have done something similar for kendo ComboBox. Do manipulate the below js function and it will work for kendo Drop Down also.
function QuestionChanged(event) {
$("[class^=security]").each(function () {
if (event.sender.element.attr('class') != $(this).attr('class')) {
var comboBox = $('#' + $(this).attr('id')).data('kendoComboBox');
$(comboBox.dataSource.data()).each(function () {
if (event.sender._selectedValue == this.Value) {
var data = this;
comboBox.dataSource.remove(data);
}
});
}
});
}
NOTE: Add security class to each of the drop down as security1 for first drop down, security2 for 2nd drop down and so on.
Hope it helps! Feel free to leave your feedback.

Categories

Resources