Place Javascript Variable within Razor Code - c#

I have one JavaScript function which adds a row into the table with the selected value in a text box. But how will i place the selected value inside the razor code ?
var val = document.getElementById("tags").value;
var strHtml2 = '#Html.TextBoxFor(x => x.extraDoc.dr_name, new {Value="Place Val Here", #class = "input1", #readonly = true })';

No it is not possible, because .NET MVC is server side code and is evaluated before being sent to the client, and javascript is Client side code which runs only once it is ON the client.
Actually you can do one thing you can get the element by using Id.
#Html.TextBoxFor(x => x.extraDoc.dr_name, new {Value="Place Val Here", #class = "input1", #readonly = true })
Razor will generate id field for the TextBoxFor probably id will be something like this: extraDoc_dr_name (or) you can find it in browser developer tool.
then you can set it using javascript:
document.getElementById("extraDoc_dr_name").value = document.getElementById("tags").value;

Try this:
var val = document.getElementById("tags").value;
var strHtml2 = '#Model.extraDoc.dr_name' ;
Update:
Now i understand what you are trying to archive.
No, you cannot mix js variable inside razor code. You can assing a razor value to a js variable, but not a js variable to a razor variable(afaik)

Related

How to get DropDownList selected Text in MVC controller

I have this DropDownList in html where i can select the Texts.Text = Project, Value = ID
#Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, #class = "form-control" })
On click submit button in the controller I can see that the Value (ID) is passed on to be posted back to DB. I want the Text to be post into DB.
Controller side code line:
detailsConfig.Project = Convert.ToString(form["Project"]);
For example:
If the dropdownlist values are
Project ID
test 1
testagain 2
In controller I should get test, not 1. Please help
You use that drop-down change event and store that name in hidden filed and get that value to controller.
View:-
#Html.DropDownList("Project", new SelectList(Model.dropConfig, "Project", "ID"), "-- Select LineID --", new { required = true, #class = "form-control",#id="ddlProject" })
<input type="hidden" id = "hdnProjectName" name="ProjectName" />
Jquery:-
$("#ddlProject").on("change", function () {
$("#hdnProjectName").val($(this).find("option:selected").text());
});
Controller:-
public ActionResult Save(FormCollection formcollection)
{
var projectName = formcollection["ProjectName"];
}
new SelectList(Model.dropConfig, "Project", "Project")
The above change solves my problem. Thanks #StephenMuecke :)
First, you should definitely strongly-type your dropdownlist to your model.
What I mean is this...
In the controller is where I would create the selectlist to be used in the view.
Controller
ViewBag.ProjectSelection = new SelectList(/* your data source */, "Project", "Project");
Disclaimer:
Submitting the Text value is not preferred because typically the Text value of the select element is not unique. Submitting the ID to the server is the best practice.. and then you can simply query the database based on the ID you submitted to get the values you want. This is the best way to get the most accurate and reliable data.
Then in your view, strongly-type your ProjectSelection selectlist to the Project property in your model.
View
#Html.DropDownListFor(model => model.Project, (IEnumerable<SelectListItem>)ViewBag.ProjectSelection, "-- Select LineID --", new { required = true, #class = "form-control" })
Why are you declaring required in the dropdownlist? That should be declared in your model.
Explanation
In MVC, when it comes to HTML elements where the user can select options to be submitted to the server (dropdownlist, listbox, etc).. only the Value will be submitted (which in your case was the ID). The Text portion of the element is just for the user to see to make their selection's easier.
Let me know if this helps!

How to get and set multiple checkbox values based on serverside data using bootstrap multiselect plugin

Here I have dropdownlist which contains multiple values. and user can select any no of values by clicking the checkbox infront of the value as shown below.
Following is my c# code.
#Html.DropDownList(m => m.Detail, new SelectList(ViewBag.detailList, "Value", "Text"), new { id = "det" , multiple= "multiple"})
$(document).ready(function() {
$('#det').multiselect();
});
When user click save button I want to get the user selected list. I am using following code to get the values.
$("#det").val()
But the above value is empty. How to get the existing selected value?
And also I want to show the values as selected based on server side values.
I am creating model and set model property with hardcoded values as below.
model.Detail = "Cheese, Tomatoes";
But these values are not getting selected in dropdownlist as well.
Used plugin here - link
Any help?
Thanks.
You need to add multiple= "multiple" in the attributes for multiselect to work.
#Html.DropDownList(m => m.Detail, new SelectList(ViewBag.detailList, "Value", "Text"),
new { id = "det", multiple= "multiple" });
to set the values:
<script>
var selectedValues = #model.Detail;
var dataarray = selectedValues.split(",");
// Set the value
$("#det").val(dataarray);
$("#det").multiselect("refresh");
</script>
First of all, use #Html.ListBoxFor that works best with Multiselect js.
In order to get the values for selected options, I have created the following client side code which returns list of value in form of String arrays
function GetDropDownVal() {
var selectidList = [];
var selectedItem = $("#ListQueCatId").val();
// .multiselect("getChecked") can also be used.
if (selectedItem != null) {
for (var i = 0; i < selectedItem.length; i++) {
selectidList.push(selectedItem[i]);
}
}
return selectidList;
}
This is how I have implemented the code
View Side Code
#Html.ListBoxFor(m => m.ListQueCatId, (SelectList)ViewBag.AllQueCat as MultiSelectList, new { #class = "form-control listQueCatIdDdl" })
Javascript Code
$(".listQueCatIdDdl").multiselect({ noneSelectedText: "--Select Category(s)--" });
Also, make sure to bind a model property of Type List in my case, ListQueCatId is List< Guid>, hence while you post the form, you will get the selected values in your model.
Also, I don't think there is need to add multiple attribute as the plugin is meant for selecting multiple values.

How to reset DropDownList Index

Im using vs'12 , C# asp.net MVC-4 - Internet Template, with KendoUI EF Code First
Logic + Question: I have first and 2ndary DropDownLists (cascading ones). So many (2ndarys) will cascade off one ( main ) DropDownList. My goal is to , with script or kendo events to On main selected index change, change all other kendo DDL's back to index(0) The cascading and enabling and all of that works fine, when i switch to another control, they all empty out, but if i were to switch back they retain there values. This is not ideal for my application
need to know
Main Kendo Control
#(Html.Kendo().DropDownListFor(m => m.Tracts)
.Name("Tracts")
.HtmlAttributes(new { style = "width:300px" }) //, id = "clients"})
.OptionLabel("Select Tract...")
.DataTextField("TractName")
.DataValueField("TractID")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetCascadeTracts", "ImageView");
});
})
2ndary Kendo Controls
#(Html.Kendo().DropDownListFor(m => m.LeaseholdA)
.Name("LeaseholdA")
.HtmlAttributes(new { style = "width:300px" })
.OptionLabel("Select LeaseholdA...")
.DataTextField("LeaseholdA")
.DataValueField("LeaseholdAID")
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetLeaseholdA", "ImageView")
.Data("filterFromTracts");
})
.ServerFiltering(true);
})
.Enable(false)
.AutoBind(false)
.CascadeFrom("Tracts")
)
Attempts
1 + 2 just tryed the 2 rimmed out section
function TractSelect(e) {
var dropdownlist = $("#LeaseholdA").data("kendoDropDownList");
//dropdownlist.SelectedIndex(0)
dropdownlist.enable(false);
};
The selectedindex(0) attempt did what it was supposed to off the ( change event ) the select even would claim selectedIndex doesn't exist
The enable worked but when i switched back they remembered where they were. so this was ineffective
Try to use the .value property of the DropDownList(kendo)
var dropdownlist = $("#LeaseholdA").data("kendoDropDownList");
dropdownlist.value(0);
These 2 lines work great
Hope this helps
the dropdownlist variable has a jquery wrapped element here
try using the below code at the same place
function TractSelect(e) {
var dropdownlist = $("#LeaseholdA").data("kendoDropDownList");
dropdownlist[0].selectedIndex = 0; //Code you need to change
dropdownlist.enable(false);
};
This will make sure that you have a html element as in plain simple javascript and YES SelectedIndex is definitely not a function but property of the HTML element
I believe you should be able to set the index to 0 using the following:
$("#LeaseholdA").val(0);
This should set the dropdown to the element with a value of 0 and thus the index.
Or you can use
$("#LeaseholdA").prop('selectedIndex', 0);

ASP.Net MVC EditorTemplate wrong Id

So I have a double field called Area. I print it this way:
<div>#Html.EditorFor(model => model.Area)</div>
My EditorTemplate for Double looks like this:
#{
var attributes = this.ViewData.ModelMetadata.ContainerType.GetProperty(this.ViewData.ModelMetadata.PropertyName).GetCustomAttributes(true);
var htmlAttributes = GAtec.AgroWeb.Basic.Ux.Web.Helpers.EditorTemplateHelper.GetAllAttributes(ViewData, attributes);
var decimalPlaces = htmlAttributes["data-format"].ToString().Split(',');
var value = decimalPlaces.Length > 1 ? Model.ToString("n" + decimalPlaces[1]) : Model.ToString();
#System.Web.Mvc.Html.InputExtensions.TextBox(this.Html, Html.NameFor(model => model).ToString(), value, htmlAttributes);
}
<script>
$(document).ready(function () {
$("##Html.IdFor(model => model)").restrictNumber();
});
</script>
Nice, but why the html element comes wrong as <input id="Area_Area" /> and the jQuery selector comes right as $("#Area") ?
Both NameFor and IdFor returns "Area" when I watch them on debbuging.
UPDATE:
My htmlAttributes(As #DarinDimitrov asked) returns this array:
["data-min": "0.0", "data-format": "0,2"]
What's the point of stuffing gazilions of inline scripts inside your view (one for each editor template), when you could simply append a class="number" to your input field and then externalize your javascript in a separate file (which is where javascript belongs) and simply use a class selector:
$(document).ready(function () {
$(".number").restrictNumber();
});
#System.Web.Mvc.Html.InputExtensions.TextBox(this.Html, "", value, htmlAttributes);
This resolved my problem. The point is, the MVC knows the model name so you don't have to say him what to print. If you do, it will concat with the model name. But why it does this, I really don't know.

How to set ID and Text in html.label helper in mvc2

I want to set ID and Text attribute in html.label helper in mvc2
<%:html.label<have to set ID and Text properties here>%>
Plz help me out..
The Html.Label method returns an HTML label element and the property name of the property that is represented by the specified expression. For example:
ASPX Syntax
<%: Html.Label("Text Content", new { id = "labelId" })%>
Razor Syntax
#Html.Label("Text Content", new { id = "labelId" })
The second parameter is the htmlAttributes, so, you can add any html attribute you want as a property of this anonymous object. For example:
new { id = "id-element", name = "name-element", size = 10, #class = "css-class" }
IdFor
If you want to take the Id by a html helper method, try to use:
#Html.IdFor(model => model.Property)

Categories