Is possible to create htmlhelpers dynamically? - javascript

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>

Related

Why can't I retrieve the value of my hidden field in javascript

From my Index_view.cshtml I have a Modal that will render the following action in my controller:
Notice the line:
public ActionResult AddContact()
{
ViewBag.Dataset = 1;
return PartialView();
}
Here is my AddContact.cshtml
See the hidden field, first line after BeginForm
<input type="hidden" id="dataset_Id" name="datasetId" value="#ViewBag.Dataset">
#model ResearchDataInventoryWeb.Models.Contact
#using (Html.BeginForm())
{
<input type="hidden" id="dataset_Id" name="datasetId" value="#ViewBag.Dataset">
<div class="section_header2">Contact</div>
<div style="padding-top:5px;">
<table>
<tr>
<td>
<span class="display-label">UCID/Booth ID</span>
</td>
<td>
#Html.TextBoxFor(model => model.Booth_UCID, new { placeholder = "<Booth/UCID>", #class = "input-box" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Type*</span>
</td>
<td>
<select class="input-box" id="contact_type">
<option value="0">Contact Type</option>
<option value="1">Dataset Admin</option>
<option value="2">Dataset Provider</option>
<option value="3">Department</option>
<option value="4">External Collaborator</option>
<option value="5">Principal Investigator</option>
<option value="6">Research Center</option>
<option value="7">Vendor</option>
</select>
<label id="contactTypeError" class="text-danger" style="display:none;">Please select a Contact Type</label>
</td>
</tr>
<tr>
<td>
<span class="display-label">Name*</span>
</td>
<td>
#Html.TextBoxFor(model => model.First_Name, new { placeholder = "<First Name>", #class = "input-box-modal" })
<label id="firstNameError" class="text-danger" style="display:none;">First name is a required field</label>
#Html.TextBoxFor(model => model.Last_Name, new { placeholder = "<Last Name>", #class = "input-box-modal" })
<label id="lastNameError" class="text-danger" style="display:none;">Last name is a required field</label>
</td>
</tr>
<tr>
<td>
<span class="display-label">Email</span>
</td>
<td>
#Html.TextBoxFor(model => model.Email, new { placeholder = "<Email 1>", #class = "input-box-modal" })
<label id="emailError" class="text-danger" style="display:none;">Email is a required field</label>
#Html.TextBoxFor(model => model.Email_2, new { placeholder = "<Email 2>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Phone</span>
</td>
<td>
#Html.TextBoxFor(model => model.Phone_Number, new { placeholder = "<Phone 1>", #class = "input-box-modal" })
<label id="phoneNumberError" class="text-danger" style="display:none;">Phone Number is a required field</label>
#Html.TextBoxFor(model => model.Phone_Number_2, new { placeholder = "<Phone 2>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Job Title</span>
</td>
<td>
#Html.TextBoxFor(model => model.Title_Role, new { placeholder = "<Job Title>", #class = "input-box" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Organization</span>
</td>
<td>
<input class="input-box" type="text" placeholder="<Organization>" />
</td>
</tr>
</table>
<div style="padding-left:10px; margin-top:10px;">
<textarea rows="3" placeholder="Notes"></textarea>
</div>
</div>
<div class="centerButton" style="margin-top: 30px;">
<div style="margin-left:30px">
<submit id="btnSubmit" class="btn btn-default btn-sm" style="padding:14px"><span class="smallText_red" style="padding:30px">SAVE</span></submit>
</div>
<div style="margin-left:30px">
<submit class="btn btn-default btn-sm" style="padding:14px"><span class="smallText_red" style="padding:30px">REMOVE</span></submit>
</div>
</div>
}
Here is my javascript
Notice the line in the script
var datasetId = $("#dataset_Id").val();
alert("dataset is " + datasetId)
<script>
$(function () {
$('#contactForm1').removeData('validator');
$('#contactForm1').removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse('#contactForm1');
function validation() {
var contactTypeVar = $("#contact_type").val();
var firstNameVar = $("#First_Name").val();
var lastNameVar = $("#Last_Name").val();
var emailVar = $("#Email").val();
var phoneNumberVar = $("#Phone_Number").val();
// Contact Type
if (contactTypeVar == "0") {
$('#contactTypeError').css("display", "block")
return false
} else {
$('#contactTypeError').css("display", "none")
return true
}
// First Name
if (firstNameVar == "") {
$('#firstNameError').css("display", "block")
return false
} else {
$('#firstNameError').css("display", "none")
return true
}
// Last Name
if (lastNameVar == "") {
$('#lastNameError').css("display", "block")
return false
} else {
$('#lastNameError').css("display", "none")
return true
}
// Email
if (emailVar == "") {
$('#emailError').css("display", "block")
return false
} else {
$('#emailError').css("display", "none")
return true
}
// Phone Number
if (phoneNumberVar == "") {
$('#phoneNumberError').css("display", "block")
return false
} else {
$('#phoneNumberError').css("display", "none")
return true
}
}
$("#btnSubmit").click(function (e) {
var formValid = validation();
if (formValid) {
var booth_ucid = $("#Booth_UCID").val();
var contact_type = $("#conact_type").val();
var first_name = $("#First_Name").val();
var last_name = $("#Last_Name").val();
var email = $("#Email").val();
var email2 = $("#Email_2").val();
var phone = $("#Phone_Number").val();
var phone2 = $("#Phone_Number_2").val();
var title_role = $("#Title_Role").val();
**var datasetId = $("#dataset_Id").val();**
**alert("dataset is " + datasetId)**
var categoryId = $("#contact_type").val();
var data = new FormData;
data.append("datasetid", datasetId);
data.append("Booth_UCID", booth_ucid);
data.append("First_Name", first_name);
data.append("Last_Name", last_name);
data.append("Email", email);
data.append("Email_2", email2);
data.append("Phone_Number", phone);
data.append("Phone_Number_2", phone2);
data.append("Title_Role", title_role);
// var frm = $('#contactForm1').serialize()
$.ajax({
type: "POST",
url: "/Dataset/AddContact/",
data: data,
contentType: false,
processData: false,
success: function (ajaxRespond) {
if (ajaxRespond.dbUpdateResult == "success") {
$("#myModal").modal("hide");
reloadContactLinks()
}
}
})
}
})
})
</script>
#Scripts.Render("~/bundles/jqueryval")
Keeps returning:
I was able to correct this issue. It turns out that the "#dataset_Id" of the hidden field on the modal, had the same "#dataset_Id" as the main screen. Once I changed the "#dataset_Id on the modal to "#contact_dataset_Id", I was able to retrieve the value of the hidden field.

How to bind dropdown value in mvc

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

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

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.

how to handle partial view elements in javascript

please refer this code and it is for a partial view of my web application developed using mvc.
#model PortalModels.WholeSaleModelUser
#using (Html.BeginForm("uploadFile", "WholeSaleTrade", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>WholeSaleModelUser</legend>
<table>
<tr>
<td>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
</td>
<td>
<div class="editor-field">
#Html.TextBoxFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</td>
</tr>
</table>
<div id="partial">
<table>
<tr>
<td>
<img id="blah" src="../../Images/no_image.jpg" alt="your image" height="200px" width="170px" />
</td>
</tr>
</table>
<script type="text/javascript">
function loadUserImage() {
var userImg = document.getElementById("blah");
var imgNm = $("#Name").value;
userImg.src = "D:/FEISPortal/FortalApplication/Img/" + imgNm + ".png";
alert(imgNm);
alert(userImg.src);
}
</script>
i need to handle the textchange event of this textbox in partial view using javascript code i have mentioned above
#Html.TextBoxFor(model => model.Name)
please somebody tell me how to handle the text change event of the above code line of textbox..
$document.on('blur', 'TextBox', function(){
//Do something
});
This format should work for any fields on a partial view. from here http://api.jquery.com/on/

Categories

Resources