how to give #readonly in DropdownListfor in asp.net MVC 4? [duplicate] - asp.net

What option do I need to set to make a drop down box readonly when using MVCs Html.DropDownList?
I've tried things like....
Html.DropDownList("Types", Model.Types, new { _Enabled = "false" })
...and many different things along this line; alas no joy!
I thought this would be an easy.....and it probably is!

Try this
Html.DropDownList("Types", Model.Types, new { #disabled = "disabled" })

Regarding the catch 22:
If we use #disabled, the field is not sent to the action (Mamoud)
And if we use #readonly, the drop down bug still lets you change the value
Workaround: use #disabled, and add the field hidden after the drop down:
#Html.HiddenFor(model => model.xxxxxxxx)
Then it is truly disabled, and sent to the to the action too.

<script type="text/javascript">
$(function () {
$(document) .ajaxStart(function () {
$("#dropdownID").attr("disabled", "disabled");
})
.ajaxStop(function () {
$("#dropdownID").removeAttr("disabled");
});
});
</script>

I had to disable the dropdownlist and hide the primary ID
<div class="form-group">
#Html.LabelFor(model => model.OBJ_ID, "Objs", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("OBJ_ID", null, htmlAttributes: new { #class = "form-control", #disabled = "disabled"})
#Html.HiddenFor(m => m.OBJ_ID)
#Html.ValidationMessageFor(model => model.OBJ_ID, "", new { #class = "text-danger" })
</div>
</div>

A tip that may be obvious to some but not others..
If you're using the HTML Helper based on DropDownListFor then your ID will be duplicated in the HiddenFor input. Therefore, you'll have duplicate IDs which is invalid in HTML and if you're using javascript to populate the HiddenFor and DropDownList then you'll have a problem.
The solution is to manually set the ID property in the htmlattributes array...
#Html.HiddenFor(model => model.Entity)
#Html.EnumDropDownListFor(
model => model.Entity,
new {
#class = "form-control sharp",
onchange = "",
id =` "EntityDD",
disabled = "disabled"
}
)

Or you can try something like this:
Html.DropDownList("Types", Model.Types, new { #readonly = "true" })

Put this in style
select[readonly] option, select[readonly] optgroup {
display: none;
}

I just do this and call it a day
Model.Id > -1 ? Html.EnumDropDownListFor(m => m.Property, new { disabled = "disabled" }) : Html.EnumDropDownListFor(m => m.Property)

#Html.DropDownList("Types", Model.Types, new { #disabled = "" })
Works

Html.DropDownList("Types", Model.Types, new { #disabled = "disabled" })
#Html.Hidden(Model.Types)
and for save and recover the data, use a hidden control

For completeness here is the HTML Helper for DropDownListFor that adds enabled parameter, when false select is disabled. It keeps html attributes defined in markup, or it enables usage of html attributes in markup, it posts select value to server and usage is very clean and simple.
Here is the code for helper:
public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, object htmlAttributes, bool enabled)
{
if (enabled)
{
return SelectExtensions.DropDownListFor<TModel, TProperty>(html, expression, selectList, htmlAttributes);
}
var htmlAttributesAsDict = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
htmlAttributesAsDict.Add("disabled", "disabled");
string selectClientId = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
htmlAttributesAsDict.Add("id", selectClientId + "_disabled");
var hiddenFieldMarkup = html.HiddenFor<TModel, TProperty>(expression);
var selectMarkup = SelectExtensions.DropDownListFor<TModel, TProperty>(html, expression, selectList, htmlAttributesAsDict);
return MvcHtmlString.Create(selectMarkup.ToString() + Environment.NewLine + hiddenFieldMarkup.ToString());
}
and usage, goal is to disable select if there is just one item in options, markup:
#Html.DropDownListFor(m => m.SomeValue, Model.SomeList, new { #class = "some-class" }, Model.SomeList > 1)
And there is one even more elegant HTML Helper example, no post support for now (pretty straight forward job, just use HAP and add hidden input as root element sibling and swap id's):
public static MvcHtmlString Disable(this MvcHtmlString previous, bool disabled, bool disableChildren = false)
{
if (disabled)
{
var canBeDisabled = new HashSet<string> { "button", "command", "fieldset", "input", "keygen", "optgroup", "option", "select", "textarea" };
var doc = new HtmlDocument();
doc.LoadHtml(previous.ToString());
var rootElements = doc.DocumentNode.Descendants().Where(
hn => hn.NodeType == HtmlNodeType.Element &&
canBeDisabled.Contains(hn.Name.ToLower()) &&
(disableChildren || hn.ParentNode.NodeType == HtmlNodeType.Document));
foreach (var element in rootElements)
{
element.SetAttributeValue("disabled", "");
}
string html = doc.DocumentNode.OuterHtml;
return MvcHtmlString.Create(html);
}
return previous;
}
For example there is a model property bool AllInputsDisabled, when true all html inputs should be disabled:
#Html.TextBoxFor(m => m.Address, new { placeholder = "Enter address" }).Disable(Model.AllInputsDisabled)
#Html.DropDownListFor(m => m.DoYou, Model.YesNoList).Disable(Model.AllInputsDisabled)

You could use this approach
Disabling all the options except the selected one:
<select>
<option disabled>1</option>
<option disabled>2</option>
<option selected>3</option>
</select>
This way the dropdown still submits, but the user can not select another value.
With jQuery
<script>
$(document).ready(function () {
$('#yourSelectId option:not(:selected)').prop("disabled", true);
});
</script>

try with #disabled and jquery, in that way you can get the value on the Controller.
Html.DropDownList("Types", Model.Types, new {#class = "your_class disabled", #disabled= "disabled" })
Add a class called "disabled" so you can enabled by searching that class(in case of multiples disabled fields), then you can use a "setTimeout" in case of not entering controller by validation attributes
<script>
function clickSubmit() {
$("select.disabled").attr("disabled", false);
setTimeout(function () {
$("select.disabled").attr("disabled", true);
}, 500);
}
</script>
submit button like this.
<button type="submit" value="Submit" onclick="clickSubmit();">Save</button>
in case of inputs, just use #readonly="readonly"
#Html.TextBoxFor("Types",Model.Types, new { #class = "form-control", #readonly= "readonly" })

You can set the select as readonly and then run some jquery to disable the options except the selected value. You cant change the value and it's included when the form is submitted.
$(document).ready(function () {
$('select option').removeAttr('disabled');
$('#readonlyTest').find('select[readonly] option').not('select[readonly] option[selected]').attr('disabled', 'disabled');
});
$('#submitButton').click(function(e) {
var formData = $('form').serialize();
$('#formData').html(formData);
});
body {
margin: 50px;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<label for="scopeReadonlyNoJs">Scope Readonly No Js</label>
<select class="form-control" id="scopeReadonlyNoJs" name="scopeReadonlyNoJs" readonly="readonly">
<option value="">Select..</option>
<option selected="selected" value="readonlyNoJsScopeValue1">Scope Value 1</option>
<option value="readonlyNoJsScopeValue2">Scope Value 2</option>
</select>
<small id="scopeReadonlyNoJsHelp" class="form-text text-muted">This is read only and no js is applied. It looks disabled but you can change the values.</small>
</div>
<div id="readonlyTest" class="form-group">
<label for="scopeReadonly">Scope Readonly</label>
<select class="form-control" id="scopeReadonly" name="scopeReadonly" readonly="readonly">
<option value="">Select..</option>
<option selected="selected" value="readonlyScopeValue1">Scope Value 1</option>
<option value="readonlyScopeValue2">Scope Value 2</option>
</select>
<small id="scopeReadonlyHelp" class="form-text text-muted">This is read only and is disabled via js by disabling the options except the selected one.</small>
</div>
<div class="form-group">
<label for="scopeDisabled">Scope Disabled</label>
<select class="form-control" id="scopeDisabled" name="scopeDisabled" disabled="disabled">
<option value="">Select..</option>
<option selected="selected" value="disabledScopeValue1">Scope Value 1</option>
<option value="disabledScopeValue2">Scope Value 2</option>
</select>
<small id="scopeDisabledHelp" class="form-text text-muted">This is disabled and wont be posted.</small>
</div>
<button id="submitButton" type="button">
Submit
</button>
</form>
<p id="formData">
</p>

I've create this answer after referring above all comments & answers.
This will resolve the dropdown population error even it get disabled.
Step 01
Html.DropDownList("Types", Model.Types, new {#readonly="readonly"})
Step 02
This is css pointerevent remove code.
<style type="text/css">
#Types {
pointer-events:none;
}
</style>
Then you can have expected results
Tested & Proven

Related

How to filter dropdownlistfor according to what has selected in first dropdownlist in asp mvc?

I am working on a asp.net mvc project and I need to filter dropdownlist according to what user has selected first dropdownlist
This is my first dropdownlist in view:
<div class="form-group">
#Html.LabelFor(m => m.BuildDefinitionName, "Build Definition name", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.BuildDefinitionName, new SelectList(Model.BuildData.Select(x => x.Key), "BuildInfo"), "select", new { #class = "form-control" })
</div>
</div>
and this is my second dropdownlist:
<div class="form-group">
#Html.LabelFor(m => m.CurrentBuildNumber, "Current Build", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.CurrentBuildNumber, new SelectList(Model.BuildData
.Where(x=>x.Key == "#BuildDefinitionName")
.Select(y => y.Value), "BuildInfo"), "select", new { #class = "form-control" })
</div>
</div>
I have a dictionary that key is string (what the user should chose first dropdown ) and value is IEnumerable ( what it should be filtered by the first dropdown selection).
I am so thanksful for solving my problem.
after applying the answer :
You need to use jquery to modify the second dropdown list.
In your 2nd dropdown list, you need to put all the data of Model.BuildData. So, in your controller, be sure to provide all the records because we will be filtering on client-side.
public ActionResult ControllerName(){
var yourModel = new yourModel();
// Add all the entries to Build Data, we're going to filter it with jquery
yourModel.BuildData = db.BuildData.ToList();
return View(yourModel);
}
In your 2nd dropdown list, we need to put a data attribute on the html. For this example, we're rendering it manually, replace your 2nd dropdown list with the HTML below.
<div class="form-group">
#Html.LabelFor(m => m.CurrentBuildNumber, "Current Build", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<select id="CurrentBuildNumber" name="CurrentBuildNumber" class="form-control">
#foreach(var selectItem in Model.BuildData){
<option data-filter="#selectItem.Key" value="#selectItem.Value">
#selectITEM.Value
</option>
}
</select>
</div>
</div>
Lastly, we need to add an onchange script to the 1st dropdown list that would filter the 2nd dropdownlist.
The code below will loop through all the options in the 2nd dropdown list, and if its data-attribute doesn't match with the selected value, it will hide it.
<script>
$(document).ready(function(){
$(document).on("change","#BuildDefinitionName",function(){
var selected = $(this).val();
$("#CurrentBuildNumber").find("options").each(function(){
if($(this).data("filter")==selected){
// if data-filter is the same as the selected value, show it
$(this).show();
}else{
// if it doesn't match, hide
$(this).hide();
}
});
});
});
</script>

Use drop down result to filter another dropdown C# MVC

I am trying to update a drop down based on the users selection in the first drop down. I found this SO post on the topic, but Im not quite sure how to add the jquery to filter values to my Razor view. Can someone point me in the right direction?
My view so far:
#using System.Security.Claims;
#model UpdateClaimFormModel;
<h2>UpdateClaimView</h2>
#using (#Html.BeginForm())
{
<select name="emailcheese">
<option selected disabled>Select User</option>
#foreach (var i in Model.UserNames)
{
<option>#i.ToString()</option>
}
</select>
<select name="authpolicy">
<option selected disabled>Select Claim:</option>
#foreach (var i in Model.UserClaims)
{
<option>#i.Type.ToString()</option>
}
</select>
<div class="form-group">
<button type="submit" class="btn btn-default">Whoo</button>
</div>
}
My Goal:
Select User [bob, bill, jim]
Select Claim: If user bob:[1,2,3], If user bill:[1,4,8], If user him:[4,5,6]
so simpley you can do something like this
#using (#Html.BeginForm())
{
<select name="emailcheese" id="selectUserNames">
<option selected disabled>Select User</option>
#foreach (var i in Model.UserNames)
{
<option>#i.ToString()</option>
}
</select>
<select name="authpolicy" id="selectAuthPolicy">
</select>
<div class="form-group">
<button type="submit" class="btn btn-default">Whoo</button>
</div>
}
now in the script part
$(function(){
var userClaims = #Html.Raw(Json.Encode(Model.UserClaims));
$(document).on('change','#selectUserNames'function(){
var selectedVal = $(this).val();
if(selectedVal == 'bob')
{
var html ='<option selected disabled>Select Claim:</option>';
for(var i=1;i<userClaims.length;++i)
{
if(i==1||i==2||i==3)
{
html=html+'<option>'+userClaims[i].Type+'</option>';
}
}
$('#selectAuthPolicy').html(html);
}
})
})
this is just a basic dea of how you can achieve this i just tried for bob there are many other ways to immplement ths

ASP.NET MVC 5 Form Validation and Error Handling

Trying to implement data validation and error handling on a simple contact form. When I add the check for ModelState.IsValid I'm in a chicken and egg situation. I have looked at other similar questions and am just not getting this. Moving from Web Forms to MVC and struggling. Trying to toggle HTML elements based on what's happening - success/error message, etc. RIght now, not even the validation is working.
Right now I'm just trying to get server-side validation working but would welcome advice on how to add client-side validation also; for example, is it necessary to use jQuery for this or is there something baked in?
View:
#using (Html.BeginForm("Contact", "Home", FormMethod.Post))
{
if (ViewData["Error"] == null && ViewData["Success"] == null)
{
<h3>Send us an email</h3>
Html.ValidationSummary(true);
<div class="form-group">
<label class="sr-only" for="contact-email">Email</label>
<input type="text" name="email" placeholder="Email..."
class="contact-email" id="contact-email">
</div>
<div class="form-group">
<label class="sr-only" for="contact-subject">Subject</label>
<input type="text" name="subject" placeholder="Subject..."
class="contact-subject" id="contact-subject">
</div>
<div class="form-group">
<label class="sr-only" for="contact-message">Message</label>
<textarea name="message" placeholder="Message..."
class="contact-message" id="contact-message"></textarea>
</div>
<button type="submit" class="btn">Send it</button>
<button type="reset" class="btn">Reset</button>
}
else if (ViewData["Error"] == null && ViewData["Success"] != null)
{
<h4>We will get back to you as soon as possible!</h4>
<p>
Thank you for getting in touch with us. If you do not hear
from us within 24 hours, that means we couldn't contact you
at the email provided. In that case, please feel free to call
us at (xxx) xxx-xxxx at any time.
</p>
}
else if (ViewData["Error"] != null)
{
<h3>Oops!</h3>
<p>
We apologize. We seem to be having some problems.
</p>
<p>
Please come back and try again later. Alternatively,
call us anytime at (xxx) xxx-xxxx.
</p>
}
}
Model:
public class ContactModel
{
[Required(ErrorMessage = "Email address is required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
[Required(ErrorMessage = "Subject is required")]
public string Subject { get; set; }
[Required(ErrorMessage = "Message is required")]
public string Message { get; set; }
}
Controller:
[HttpPost]
public ActionResult Contact(ContactModel contactModel)
{
if (ModelState.IsValid)
{
try
{
MailMessage message = new MailMessage();
using (var smtp = new SmtpClient("mail.mydomain.com"))
{
// Standard mail code here
ViewData["Success"] = "Success";
}
}
catch (Exception)
{
ViewData["Error"]
= "Something went wrong - please try again later.";
return View("Error");
}
}
return View();
}
Error View:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Error</title>
</head>
<body>
<hgroup>
<h1>Error.</h1>
<h2>An error occurred while processing your request.</h2>
</hgroup>
</body>
</html>
UPDATE - 05/09/2017
Per Guruprasad's answer, if ModelState.IsValid evaluates to false, then no validation error messages are being reported on the form.
Note I had to change the AddModelError signature to not use the "Extension ex" parameter:ModelState.AddModelError("Error", "Server side error occurred"); as I do not want system errors being reported to users.
Note also that at this point I am only trying out validation on the server side (have yet to work through client-side validation).
I have updated the Contact.cshtml view as follows as no model errors were being displayed - I have included the Bootstrap .has-error and .help-block CSS rules for the validation errors:
#using (Html.BeginForm("Contact", "Home", FormMethod.Post))
{
<h3>Send us an email</h3>
Html.ValidationSummary(true);
<div class="form-group has-error">
<label class="sr-only" for="contact-email">Email</label>
#Html.TextBoxFor(m => m.Email, new { type = "text", name = "email",
placeholder = "Email..", #class = "contact-email" })
#Html.ValidationMessageFor(model => model.Email, String.Empty,
new { #class="help-block" })
</div>
<div class="form-group has-error">
<label class="sr-only" for="contact-subject">Subject</label>
#Html.TextBoxFor(m => m.Subject, new { type = "text",
name = "subject",
placeholder = "Subject..", #class = "contact-subject" })
#Html.ValidationMessageFor(model => model.Subject, String.Empty,
new { #class = "help-block" })
</div>
<div class="form-group has-error">
<label class="sr-only" for="contact-message">Message</label>
#Html.TextAreaFor(m => m.Message, new { name = "message",
placeholder = "Message..", #class = "contact-message" })
#Html.ValidationMessageFor(model => model.Message, String.Empty,
new { #class = "help-block" })
</div>
<button type="submit" class="btn">Send it</button>
<button type="reset" class="btn">Reset</button>
if (ViewData["Success"] != null)
{
<h4>We will get back to you as soon as possible!</h4>
<p>
Thank you for getting in touch with us. If you do not hear
from us within 24 hours, that means we couldn't contact you
at the email provided. In that case, please feel free to
call us at (xxx) xxx-xxxx at any time.
</p>
}
}
There are multiple things you need to understand here. Let me go point by point.
Its good to know that you have your model designed, but how your view gets to know that it has a model to bind for itself and when posting the form contents, how would server comes to know that, there is a model to be received. So on the first instance, you need to construct your view binding the model. To bind a model in a view, you need to first get a reference/declare it at the top, letting view know that, ok, here is a model for you to generate my view.
Well, you have ValidationSummary to true, then I would suggest that, instead of using ViewData to pass error message, you can use ModelState.AddModelError and let ValidationSummary take care of that. As a side note, you might also want to take care of this issue and you can resolve the same with answers mentioned in the same post. If you are not using or do not want to use Html.ValidationSummary, then you can stick to your current view.
Now, to display Success message, you can either use TempData or ViewData and follow the same structure as you have in your view now. Here is one more post to let you work on that.
Last and most important on View part is binding model properties to View elements. Use Razor View extension helpers to generate View for your model. You have #Html.TextBoxFor,#Html.TextAreaFor etc., You also have #Html.TextBox, #Html.TextArea which is not for binding model properties, but just to generate a plain HTML view. You can add other html properties within these helpers as shown in the updated view below. I would suggest to dig down more on the overloads available for these helpers.
So here is your updated view.
#model SOTestApplication.Models.ContactModel #*getting model reference*#
#using (Html.BeginForm("Contact", "Home", FormMethod.Post))
{
<h3>Send us an email</h3>
Html.ValidationSummary(true);
<div class="form-group">
<label class="sr-only" for="contact-email">Email</label>
#Html.TextBoxFor(m => m.Email, new { type = "text", name = "email", placeholder = "Email..", #class = "contact-email" })
#*Usage of helpers and html attributes*#
</div>
<div class="form-group">
<label class="sr-only" for="contact-subject">Subject</label>
#Html.TextBoxFor(m => m.Subject, new { type = "text", name = "subject", placeholder = "Subject..", #class = "contact-subject" })
</div>
<div class="form-group">
<label class="sr-only" for="contact-message">Message</label>
#Html.TextAreaFor(m => m.Message, new { name = "message", placeholder = "Message..", #class = "contact-message" })
</div>
<button type="submit" class="btn">Send it</button>
<button type="reset" class="btn">Reset</button>
}
if (ViewData["Success"] != null)
{
<h4>We will get back to you as soon as possible!</h4>
<p>
Thank you for getting in touch with us. If you do not hear
from us within 24 hours, that means we couldn't contact you
at the email provided. In that case, please feel free to call
us at (xxx) xxx-xxxx at any time.
</p>
}
Controller Side validation
Not much to say on this part as it looks good. But based on few of my points above, I would suggest you to add ModelState.AddModelError instead of using ViewData for error messages. Eliminate your if conditions in view, so that contact form remains, even after postback. Now if you want to persist the values after server side validation, then just pass back the model to your view in your post method. Updated Controller would be:
[HttpPost]
public ActionResult Contact(ContactModel contactModel)
{
if (ModelState.IsValid)
{
try
{
MailMessage message = new MailMessage();
using (var smtp = new SmtpClient("mail.mydomain.com"))
{
// Standard mail code here
ViewData["Success"] = "Success";
}
}
catch (Exception)
{
ModelState.AddModelError("Server side error occurred", ex.Message.ToString());
}
}
return View(contactModel); //this will persist user entered data on validation failure
}
Client Side Validation
As far as this portion is considered, you have few more things to set up in your application.
You need to add Html.EnableClientValidation(true); and Html.EnableUnobtrusiveJavaScript(true); to your application. There are various possible ways to add this. You can add this on Web.config file under appSettings for global implication Or you can add this in particular view as mentioned in below updated View example.
Global Implication in Web.Config ex:
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
If you have noticed your BundleConfig.cs file under App_Start directory, you would have seen below entries created by default. These are the jquery stuffs responsible for your Client Side validation.
jQuery and jQueryVal entries
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
Next Step is to add reference to these files/use #section Scripts to render these bundles either in _Layout.cshtml or in any specific view. When you include this in _Layout.cshtml. these scripts/bundles are rendered wherever you use this layout with other views. So basically, its your call on where to render these.
For example here, I would render these in Contact.cshtml view soon after adding reference to model.
#section Scripts
{
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
}
One Last thing to make this work here is that you need to use #Html.ValidationMessageFor razor extension and let MVC do the binding of error messages on particular properties. Also for these error messages to be displayed in the View, you need to specify ErrorMessage for each property in your model as you are doing it now with Required(ErrorMessage=... for each properties in model. There are more to know about these stuffs if you explore it in detail.
Your updated view with proper validations added.
#model SOTestApplication.Models.ContactModel
#section Scripts
{
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
}
#using (Html.BeginForm("Contact", "Contacts", FormMethod.Post))
{
<h3>Send us an email</h3>
Html.ValidationSummary(true);
Html.EnableClientValidation(true);
Html.EnableUnobtrusiveJavaScript(true);
<div class="form-group">
<label class="sr-only" for="contact-email">Email</label>
#Html.TextBoxFor(m => m.Email, new { type = "text", name = "email", placeholder = "Email..", #class = "contact-email" })
#Html.ValidationMessageFor(m => m.Email)
</div>
<div class="form-group">
<label class="sr-only" for="contact-subject">Subject</label>
#Html.TextBoxFor(m => m.Subject, new { type = "text", name = "subject", placeholder = "Subject..", #class = "contact-subject" })
#Html.ValidationMessageFor(m => m.Subject)
</div>
<div class="form-group">
<label class="sr-only" for="contact-message">Message</label>
#Html.TextAreaFor(m => m.Message, new { name = "message", placeholder = "Message..", #class = "contact-message" })
#Html.ValidationMessageFor(m => m.Message)
</div>
<button type="submit" class="btn">Send it</button>
<button type="reset" class="btn">Reset</button>
if (ViewData["Success"] != null)
{
<h4>We will get back to you as soon as possible!</h4>
<p>
Thank you for getting in touch with us. If you do not hear
from us within 24 hours, that means we couldn't contact you
at the email provided. In that case, please feel free to call
us at (xxx) xxx-xxxx at any time.
</p>
}
}
Hope I have clarified most of your doubts with these points. Happy Coding.. :)

How can i get a dropdownbox working with a css class?

I have a SelectList in the controller that its value passed to the view by ViewData to the view as below:
List<string> available = new List<string>();
available.AddRange(product.AvailableSizes.Split(',').ToList());
ViewData["availablesize"] = new SelectList(available);
in the view i have a drop down box which display the values of the variable availablesize as below:
#Html.DropDownList("availablesize")
for some reasons i need to display this drop down box in the following format but unable to handle this issue any suggestion?
<div class="product-page-options">
<div class="pull-left">
<label class="control-label">Size:</label>
<select class="form-control input-sm">
<option>L</option>
<option>M</option>
<option>XL</option>
</select>
</div>
</div>
This code must work, you can give css attributes as well in the razor syntax.
Also Make sure your ViewData["availablesize"] has IEnumerable<SelectListItem>
Change your controller code to below
ViewData["availablesize"] = new SelectList((IEnumerable)available);
in Views syntax must be like below
<div class="product-page-options">
<div class="pull-left">
<label class="control-label">Size:</label>
#Html.DropDownList("availablesize", ViewData["availablesize"], new {#class = "form-control input-sm "})
</div>
</div>
This is the syntax that you require
If you want to style each option differently, depending on the values passed, you can use some JQuery for that:
$(document).ready(function() {
$("#availablesize option").each(function() {
if ($(this).val() != '') {
switch ($(this).val()) {
case 'S':
$(this).css('background-color', 'lightgreen');
break;
case 'M':
$(this).css('background-color', 'green');
break;
case 'L':
$(this).css('background-color', 'orange');
break;
case 'XL':
$(this).css('background-color', 'red');
break;
default:
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="availablesize">
<option value="">- select size -</option>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
Fiddle

how to get the selected value from a drop down list and transfer it to a viewbag

View
...Some Codes...
<select class="form-control" style = "width:400px">
<option selected> select issue type </option>
#foreach( var item in Model._issueList)
{
<option>#item.issueName</option>
}
</select>
...Some Codes...
Output of my dropdown
dropDown: issue_one, issue_two, issue_three
Now I want to choose my issue_three in my drop down and save it in a Viewbag.select, want should be the proper code so that I can transfer the issue_three to my Viewbag.select
TEST
...foreach code...
Viewbag.select = ????
View
<select class="form-control" style = "width:400px">
<option selected> Select Company Name </option>
#foreach (var item in Model._issueList)
{
<option id="issueSelect" onclick="transferIssue('#item.issueNo')">#item.issueName</option>
}
</select>
#Html.HiddenFor( m => m.variable,new { #class = "form-control", style = "width:400px", #id = "issue" })
...Some codes...
<button type ="submit" id='submit_button'>Submit</button>
SCRIPT Use JQUERY
function transferIssue(x){ $('#issue')val(); }
jQuery(document).on('click', '#submit_button', function (ev) {
ev.preventDefault();
var _issue = jQuery('#issue').val();
var _url = '#Url.Action("Jobs")' + '?value='+ _issue;
window.location.href = _url;
});

Resources