CSharp · Mvc
using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Web.Mvc;
namespace HelloWorldMvcApp
{
public class SampleViewModel
{
public string Level { get; set; }
public List<SelectListItem> Levels { get; set; }
}
}
@model HelloWorldMvcApp.SampleViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<!-- template from http://getbootstrap.com/getting-started -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<!-- CSS Includes -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<style type="text/css">
.field-validation-error {
color: #ff0000;
}
</style>
</head>
<body>
<div class="container">
<div class="col-md-6 col-md-offset-3">
<h1>DropDownListFor with JS</h1>
@using (Html.BeginForm())
{
<div id="test" class="form-group">
</div>
}
<br/><br/>
<div class="alert alert-warning fade">
<img src="http://entechprod.blob.core.windows.net/dotnetfiddle/morpheus.jpg" style="max-width:100%;"/><br/><br/>
<strong><span class="alert-content"></span></strong>
</div>
</div>
</div>
<!-- JS includes -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>
<script type="text/javascript">
function openAlert(txt) {
$('.alert-content').text(txt);
$('.alert').addClass('in');
}
function closeAlert() {
$('.alert').removeClass('in');
}
$(function(){
var levelDropdown = '@Ajax.JavaScriptStringEncode(Html.DropDownListFor(m => m.Level, Model.Levels, null, null).ToHtmlString())';
console.log(levelDropdown);
var level = "<div class='col-sm-3 search-spacing'><label for='Level'>Level</label>" +
levelDropdown.replace(/(\r\n\t|\n|\r\t)/gm,"") +"</div>";
$('#test').append(level);
});
</script>
</body>
</html>
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace HelloWorldMvcApp
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
var model = new SampleViewModel();
model.Levels = new List<SelectListItem>() {
new SelectListItem() { Text = "Option 1", Value = "1" },
new SelectListItem() { Text = "Option 2", Value = "2" },
new SelectListItem() { Text = "Option 3", Value = "3" },
new SelectListItem() { Text = "Option 4", Value = "4" }
};
return View(model);
}
}
}