asp.net mvc get values from multiple dropdown - javascript

Below is my code where the i get data from 2 viewbags. one viewbag has the property lists and the other one is a dropdown. how do i get the property list and its corresponding value in the javascipt.
asp.mvc razor view code:
#if (ViewBag.ddlcolmapping != null && ViewBag.excelheaders != null)
{
foreach (var proplists in ViewBag.ddlcolmapping)
{
<div>
<a data-id='#proplists' id='ColumnSelect_#(proplists)' href="#" class="select-categories">#proplists</a>
#Html.DropDownList("ddl", new SelectList(ViewBag.excelheaders), new { #id = #proplists })
<br/><br/>
</div>
}
}
Javascript code
function SaveMapping(elem) {
debugger;
...
}
}

I can offer a solution using JQuery. I'd give some class name to the outer div something like
<div class="someDiv">
<a data-id='#proplists' id='ColumnSelect_#(proplists)' href="#" class="select-categories">#proplists</a>
#Html.DropDownList("ddl", new SelectList(ViewBag.excelheaders), new { #id = #proplists })
<br/><br/>
</div>
And then in the javascript using JQuery, you can do call the following code on some click or any event that you are using to capture the anchor tag text and the selected value from the dropdown. I have thrown some alert to show you how you can pull the value.
$("div.someDiv").each(function () {
alert($(this).find('a').text());
alert($(this).find('select>option:selected').text());
})

Related

How to send a user choice from a controller view to another?

I have three divs like this:
<div onclick="GoToContactPage()">
#*Some Code*#
</div>
<div onclick="GoToContactPage()">
#*Some Code*#
</div>
<div onclick="GoToContactPage()">
#*Some Code*#
</div>
on the GotoContactPage() function I only have a redirect link to another view like that
function GoToContactPage() {
window.location.href = '/Home/SecondView';
}
and in that /SecondView I have an input method like that:
<div class="col-md-5">
#Html.TextBoxFor(m => m.Name, new { placeholder = "Name", #class = "form-control", #id= "name"})
</div>
All I was trying to do, when the user choose the first div a specific text appears in the input method in the other view, and so to the another two divs. I was thinking about sending an int then having an if statements and also was thinking about sending the string itself in the OnClick function but don't know what to do? and which is better? What should I do, Please?
You should pass an id in GoToContactPage(id) so that function takes an argument an run according to it.
function GoToContactPage(id) {
if(id== ""){
//your conditions
}else if(id ==""){
//your conditions
}else{
//your conditions
}
}
To get data in Second page pass it through the url www.example.com?id=1&name=xyz and get them on second page by $_GET method.

use jquery variable in # block razor

I'm strugling with a jquery script inside a cshtml page. For short my question is how to use a var inside a # statement in a cshtml page?
below an example of what I'm trying:
<select id="DefaultText">
<option value="-1">-- select --</option>
#foreach( var d in Model.DefaultTexts )
{
<option value="#d.Id" >#d.Name</option>
}
</select>
<script type="text/javascript">
$('#DefaultText').change(function () {
var id = parseInt($('#DefaultText :selected').val());
var text = #Model.DefaultTexts.First( t => t.Id == id );
$('#CustomProductText').val(text);
});
</script>
I can't reach the var id. It's out of scope. I've also tryed it with a for loop and a if statement. But in the if statement I get the same error: out of scope.
The full story is this:
On my page I've a dropdown list. The items to select are short names for default text parts. Based on the id or name, I want to show the default text part in a textbox.
#CustomProductText is my textbox where the content should be placed (code not posted).
I've also tryed it with #: and statement but that did not work.
What am I doing wrong or maybe its not even possible what I'm trying to do.
As an alternative I've added a action to my controller to get the text form there. Below the code:
<script type="text/javascript">
$('#DefaultText').change(function () {
var id = parseInt($('#DefaultText :selected').val());
$.post("Categories/GetDefaultText", { Id: id }, function (data) {
alert(data);
});
//$('#CustomProductText').val(text);
});
</script>
controller code:
[HttpPost]
public ActionResult GetDefaultText(int id)
{
using( var context = new MyContext() )
{
var text = context.DefaultText.First( d => d.Id == id ).Text;
return this.Content( text );
}
}
This doesn't work. The action doesn't get hit in debug mode.
regards,
Daniel
The $.post that is not working for you, you should prefix the url with / sign and it will be hit as expected:
$.post("/Categories/GetDefaultText", { Id: id }, function (data) {
alert(data);
});
As for the razor solution, you can't use javascript variables in the razor code as it's not a scripting language. What razor does is simply rendering the strings (be it html or javascript or anything) into the page.
To do what you want you either need to request the server to pass the text to your page or render all the texts you have in the page and then access this rendered content in your javascript.

Adding JavaScript to MVC 4 .NET Bootstrap Web App

So I built this nice MVC 4 web app, I initially stayed away from fancy CSS and JS and just focused on getting it to work. I got to work, then I decide lets add bootstrap too it make it look pretty. Now I would like to add some basic java script. Some stuff like:
<button class="btn btn-default" type="button" onclick="javascript:document.getElementById('elementid').value=0;">Remove</button>
I have a List of parts, a part as a quantity, a number and name. So I loop through the list.
#foreach (Hardware hw in Model.HardwareList)
{
<div class="row">
<div class="col-lg-2">
#Html.EditorFor(h => hw.Quantity, "Int32")
</div>
<div class="col-lg-2">
#Html.DisplayFor(h => hw.Partnumber)
</div>
<div class="col-lg-8">
#Html.DisplayFor(h => hw.PartName)
</div>
</div>
}
My custom editor, is textbox with some bootstrap css to make look pretty. This generates nice simple view but all of my text boxes have a nameof "hw.Quantity" and id of "hw_Quantity". So I can't use getElementById(), if I change the id the textboxes when I go to post the model, I get null list. I feel like I must be missing something super simple.
editor template
#model int?
#{
int i;
if (!Model.HasValue)
{
i = 0;
}
else
{
i = Model.Value;
}
var htmlAttributes = new RouteValueDictionary();
if (ViewBag.#class != null)
{
htmlAttributes.Add("class", "form-control " + ViewBag.#class);
}
else
{
htmlAttributes.Add("class", "form-control");
}
if (ViewBag.placeholder != null)
{
htmlAttributes.Add("placeholder", ViewBag.placeholder);
}
}
<div class="form-group#(Html.ValidationErrorFor(m => m, " has-error")) input-group">
#Html.TextBox(
"",
ViewData.TemplateInfo.FormattedModelValue,
htmlAttributes)
#Html.ValidationMessageFor(m => m, null, new { #class = "help-block" })
</div>
I'm assuming you have the remove button for every row, on click of that button you can execute a javascript function that can look into the clicked button's parent ".row" and change the "hw.Quantity" value in that row. Like
onclick="javascript:$(this).parents('.row').find('elementid').val(0);"
Additionally you can use Html's data- attributes to store additional data..
For each row add unique "data-" attribute , maybe row id. I am sure you have to have an Id per a row.
htmlAttributes('data-id', {rowid})
You will have to pass this rowId to your custom editor.
Than If you have a remove or clear button per row you can add simple javascript on it
<button class="btn btn-default" type="button" onclick="$('[data-id=#rowId]').val(0)">Remove</button>

Add options to the dropdownlist added after button click using partial view

I have a form which allows adding cities. Each city is added by clicking the Add button and then selecting the city from the drop down list. The first drop down list is shown initially. When clicking the addCity button it calls the Controller action AddCity and returns the partial view. The drop down list is populated from a map object where keys are the name of cities. The javascript file behind the cshtml does the work of populating the dropdown list. The first dropdownlist is populated because it is available when document is ready. After clicking the Add button, how should I make sure that the new drop down list also has the cities in its options.
Here is my main view and partial view.
MainView.cshtml
<form id="myForm">
<div id="info">
#Html.Partial("_City")
</div>
<button id="addCity" class="btn" data-url='Url.Action("AddCity")'> Add </button>
</form>
_City.cshtml
<div class="city-info">
<div class="row">
<ul class="dropdown-menu cityList"></ul>
</div>
</div>
The Controller class has:
public ActionResult AddCity()
{
return PartialView("_City");
}
The javascript file code has:
var cityMap = {...some data...}
// Add new city on button click
$(function () {
$('#addCity').click(function (e) {
e.preventDefault();
var $infoDiv = $('#info');
var url = $(this).data('url');
$.get(url, function (data) {
$infoDiv.append(data);
});
});
});
$(document).ready(function () {
$.each(cityMap, function (key, value) {
$(".cityList").append("<li> <a tabindex=\"-1\" href=\"#\">" + key + "</a> </li>");
});
}
How can I apply the same function to the newly added cityList items? I tried some jquery but I fail to find the newly added dropdownlist (cityList) element.

How to display value of a ViewBag in my view with a JS function?

I want to display the data from a ViewBag in my View with Javascript. Here is my code.
View
<span id='test'></span>
Javascript
function myFunction()
{
$('#test').text('#ViewBag.Test');
}
When myFunction() is called I get the text #ViewBag.Test but not his value. How can I fix this ?
You need to place your JavaScript which takes the #ViewBag.Test value in a page which is interpreted by the Razor view engine. My guess is that this is currently not the case.
If you want to keep your javascript codebase separate from the view (which is entirely reasonable) you can use a global variable:
// in the view:
var testText = '#ViewBag.Test';
// in external js
function myFunction() {
$('#test').text(window.testText);
}
Alternatively, you can use a data-* attribute:
<span id='test' data-text="#ViewBag.Test"></span>
// in external js
function myFunction() {
$('#test').text(function() {
return $(this).data('text');
});
}
What you should be ideally doing is passing the data to the view with a view model. Have a property to store that value you want to pass. For example. Let's think about a page to show the customer details and you want to get the last name in your javascript variable.
Your GET action method
public ActionResult View(int id)
{
var vm=new CustomerViewModel();
vm.LastName="Scott"; // You may read this from any where(DAL/Session etc)
return View(vm);
}
and in your view which is strongly typed to your view model.
#model CustomerViewModel
<div>
Some Html content goes here
</div>
<script type="text/javascript">
var lastName="#Model.LastName";
//Now you can use lastName variable
</script>
EDIT : (As per the question edit) To show the content on some event (ex : some button click), Store the value somewhere initially and then read it as needed and set it wherever you want.
#model CustomerViewModel
<div>
<span id="content"></span>
#Html.HiddenFor(s=>s.LastName)
<input type="button" id="btnShow" value="Show content" />
</div>
<script type="text/javascript">
$(function(){
$("btnShow").click(function(e){
$("#content").html($("#LastName").val());
});
});
</script>
Firstly make sure your ViewBag.Test does got a value, then use a div tag instead of a span and add the following code:
<script type="text/javascript">
$(document).ready(function () {
StartRead();
});
function StartRead() {
document.getElementById("test").innerHTML = '#ViewBag.Test';
}
</script>

Categories