I need to define below code as a global variable in the View and then I could use that value in my separate JS code. I don't know how to do this, I tried various things.
<td class="choice">
#Html.TextBoxFor(modelItem => item.ManualDate, new { #type = "date", #class = "form-control datepicker" }) //I want this #Html... to be global and available in .js file
</td>
So this part of my View should be declared somewhere on the top of partial View? In curly brackets?
#{
ViewBag.Title = "myTitle";
Layout = "~/Views/Shared/_Layout.cshtml";
var globalVar = "#Html.TextBoxFor(modelItem => item.ManualDate, new { #type = 'date', #class = 'form-control datepicker' })";
}
I refer to it in .js file but it doesn't work properly (in 'choice' data field string is showed instead of razor element):
finalChoice.innerHTML = '#Model.globalVar'
The razor syntax like #Html.TextBoxFor and #Model can only be parsed by the server, not JavaScript. Using variables in #{//...} will be parsed as a string. The JavaScript file in the parent page can directly call the elements in the partial view.
#Html.TextBoxFor can be placed in the view. But if you don’t want to show it in the view, please set its style to hide. Then you can get this element via its id.
In _part.cshtml(partial view)
<div id="part">
#Html.TextBoxFor(modelItem => modelItem.ManualDate, new { #type = "date", #class =
"form-control datepicker" })
</div>
example
Related
In my ASP.NET MVC web application, I send some data to the combo box using the view bag from the controller to the view.
In the view, there is a javascript when the combo box value is changed, I send that value to the controller again using an ajax call and get the related data, and show it in another textbox.
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName");
View
<div class="form-group row">
#Html.LabelFor(model => model.Task_Assigned_Branch_Id, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-sm-8">
#Html.DropDownList("Task_Assigned_Branch_Id", null, "Select the Branch", new { #class = "form-control js-dropdown js-Branch", #Id = "Branch" })
#Html.ValidationMessageFor(model => model.Task_Assigned_Branch_Id, "", new { #class = "text-danger" })
</div>
</div>
Javascript
$('.js-Branch').change(function () {
GetBranchMembers($(this).val())
});
This worked perfectly.
Then I want to change it, when sending the data to the view bag, I wanted to select a default value to the combo box and send it to the view.
So I changed the controller code to
ViewBag.Task_Assigned_Branch_Id = new SelectList(db.Branch.Where(x=>x.Status ==true), "Id", "BranchName", branchId);
Now the value is loading as the default selected value in the combo box.
So to get the combo box value in the loading event I wrote this
$(document).ready(function ()
{
var e = document.getElementById("js-Branch");
alert(e);
GetBranchMembers(e)
})
But the id returns null.
I guess because I sent the default value to the combo box, it doesn't pass the id to the script or something. Is there any other way of doing this?
Try using below code. i think you are using wrong id. you are using a class name in getElementbyId function
$(document).ready(function ()
{
var e = document.getElementById("Branch");
alert(e);
GetBranchMembers(e)
});
I am passing data from the Controller to the View using the ViewData
Code in the controller:
public ActionResult Create()
{
ViewData["gN"] = new SelectList(db.gT, "id", "gN");
return View();
}
In the View I am using #Html.EditorFor() to create the new item for our table which we store in the database.
<div class="col-md-10">
#Html.EditorFor(model => model.gT.gN, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.groupid, "", new { #class = "text-danger" })
</div>
When I am using #Html.DropDownList our list of gN is perfectly showing as the dropdown list
#Html.DropDownList("gN", null, htmlAttributes: new { #class = "form-control" })
I want to use EditorFor() so that when the user starts typing in the input box, the dropdown list appears below it. and if that text which user is typing, present in the dropdown then the user can select it.
How we should show the list gN (which we are getting using ViewData from Controller) in the EditorFor() HTML element?
The Html.EditorFor() method always creates an <input> element, though the type attribute can vary depending on the model property type. HTML5 actually supports exactly what you want with the <datalist> element, which you tie to an <input> element with the list attribute. the <datalist> element takes child <option> elements containing the values you want in the list.
Making some guesses about your models here...
// Controller
public ActionResult Create()
{
ViewData["gN"] = db.gT;
return View();
}
// View
#Html.EditorFor(model => model.gT.gN, new { htmlAttributes = new { #class = "form-control", list="gN-datalist" } })
<datalist id="gn-datalist">
#foreach (var item in (gT)ViewData["gN"])
{
<option value="#item.id">#item.gN</option>
}
</datalist>
You could also create an HtmlHelper extension method that would create this for you.
Here i am using anchor tag for this class is not applying.And this is my code
<td> #CAH.BookingID</td>
Previously i used
<td> #Html.ActionLink((string)CAH.BookingID, "ViewServiceDetails", "ServiceConsumer", new { BookingID = CAH.BookingID }, new { #class = "btn btn-link", data_toggle = "modal", data_target = "#ViewServiceDetails" })</td>
but iam getting error for second one
You're going about this wrong.
You're getting mixed up with 'normal' HTML, and helpers.
You don't pass in your #class attributes to the anonymous object passed to Url.Action
Just use normal HTML in conjunction with Url.Action if you want:
You're going about this wrong.
You're getting mixed up with 'normal' HTML, and helpers.
You don't pass in your #class attributes to the anonymous object passed to Url.Action
Just use normal HTML in conjunction with Url.Action if you want:
<td>
<a href="#Url.Action("ViewServiceDetails", "ServiceConsumer", new { BookingID = CAH.BookingID })"
class="btn btn-link"
data-toggle="modal"
data-target="#ViewServiceDetails">
#CAH.BookingID
</a>
</td>
You could use Html.ActionLink as described here
#Html.ActionLink(CAH.BookingID, // <-- Text of link.
"ServiceConsumer", // <-- Controller Name.
"ViewServiceDetails", // <-- ActionMethod
new { BookingID = CAH.BookingID }, // <-- Route arguments.
new { #class="btn btn-link", data_toggle = "modal", data_target = "#ViewServiceDetails" } // <-- htmlArguments
)
I am trying to disable or enable a dropdownlistfor in my mvc application based on model property:-
what I am doing is :-
#Html.DropDownListFor(m => m.ParentOrganisationID, new SelectList(Model.ParentOrganisations, "ID", "Name", Model.ParentOrganisationID), new { #id = "ddlParentOrganisations", #class = "form-control css-select", #disabled = Model.IsReadOnly ? "disabled" : "false", #style = "width:40%; height:10%;" })
but even if model property "model.IsReadOnly" is false, then also it is showing the dropdown as disabled.
Please suggest how to handle this, without using any javascript
Thanks in advance
It is not possible to include the condition (if/ternary statement(s)) inside the call to the DropDownListFor helper method because you cannot pass a line of c# code (with your if condition) where it expects an object for html attributes. Also all of the below markups will render a disabled SELECT.
<select disabled></select>
<select disabled="disabled"></select>
<select disabled="false"></select>
<select disabled="no"></select>
<select disabled="usingJqueryEnablePlugin"></select>
<select disabled="enabled"></select>
You can simply check the value of your Model property with an if condition and conditionally render the disabled version.
#if (!Model.IsReadOnly)
{
#Html.DropDownListFor(s => s.ParentOrganisationID,
new SelectList(Model.ParentOrganisations, "ID", "Name"))
}
else
{
#Html.DropDownListFor(s => s.ParentOrganisationID,
new SelectList(Model.ParentOrganisations, "ID", "Name"),new {disabled="disabled"})
}
You may consider creating a custom html helper method which takes care of the if condition checking.
public static class DropDownHelper
{
public static MvcHtmlString MyDropDownListFor<TModel, TProperty>
(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectItems,
object htmlAttributes,
bool isDisabled = false)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression,
htmlHelper.ViewData);
IEnumerable<SelectListItem> items =
selectItems.Select(value => new SelectListItem
{
Text = value.Text,
Value = value.Value,
Selected = value.Equals(metadata.Model)
});
var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (isDisabled && !attributes.ContainsKey("disabled"))
{
attributes.Add("disabled", "disabled");
}
return htmlHelper.DropDownListFor(expression,items, attributes);
}
}
Now in your razor view,call this helper
#Html.MyDropDownListFor(s=>s.ParentOrganisationID,
new SelectList(Model.ParentOrganisations, "ID", "Name")
,new { #class="myClass"},Model.IsReadOnly)
This is an HTML basic rule: from the moment you set the attribute disabled (regardless of its value), the element will be disabled.
To get what you want, you need to create an HTML extension DropDownListFor.
Please see this link.
The accepted answer from Shyju works great. But what if you want to use HTML5 data-* attributes in your custom helper? The standard MVC DropDownListFor provides a workaround by using an underscore (_) in place of the dash (-). And that helper is intelligent enough to convert the underscores to dashes when the markup is rendered.
Here is a custom helper that will provide a parameter to disable a DropDownList and also converts the HTML5 data-* attributes appropriately. It also preserves any other values passed in via the htmlAttributes parameter. The code is a little more concise as well (imo).
public static MvcHtmlString MyDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> list, string optionLabel, object htmlAttributes, bool disabled)
{
var routeValues = new System.Web.Routing.RouteValueDictionary();
// convert underscores to dashes...
foreach (System.ComponentModel.PropertyDescriptor property in System.ComponentModel.TypeDescriptor.GetProperties(htmlAttributes))
{
routeValues.Add(property.Name.Replace('_', '-'), property.GetValue(htmlAttributes));
}
if(disabled)
{
routeValues.Add("disabled", "disabled");
}
return htmlHelper.DropDownListFor(expression, list, optionLabel, routeValues);
}
And the markup:
#Html.MyDropDownListFor(m => m.MonthId, Model.Months, "Select Month", new { #class = "form-control", data_url = Url.Action("GetMonths") }, Model.IsDisabled)
I have a Hidden field in a Partial View
#Html.HiddenFor(model => model.Type, new { id = "Type" })
In my JS for the page in document.ready function I am trying to get the value for this Field using:
var type = $('#Type').val();
alert(type);
The value Type is set in two partial views which then Render the other Partial View as below:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
{ Model.Type = TypeEnum.Diesel; }
<p>
#{ Html.RenderPartial("_MyOtherView"); }
</p>
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
{ Model.Type = TypeEnum.Petrol; }
<p>
#{ Html.RenderPartial("_MyOtherView"); }
</p>
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
{ Model.Type = TypeEnum.Electric; }
<p>
#{ Html.RenderPartial("_MyOtherView"); }
</p>
}
However when I naviagte between the Tabs which load the content the alert only ever fires with the 'Diesel' value - I change the HiddenFors to TextBoxFor and on screen I can see the contents of the textbox gets updated to Diesel/Petrol/Electric on moving between Tabs but I cannot figure out why the alert is not getting changed?
Unless you used "Type" as an example ID, you seem to be rendering three partial views, each containing a hidden input with ID "Type". The result is a page with three inputs with the same ID, causing a conflict if you're trying to get their value the way you did in your script.
I suggest putting classes on them, for example "hiddenInput", and then updating your script to something similar to this:
$('.hiddenInput').each(function() {
alert($(this).val();
});