I have a MVC3 application that populates a dropdownlist from a Model. When I select an item from the list , i would like to Update the url ('/Edit/4') on a single 'edit' link which will allow me display the edit view, i.e rather than use a template which creates edit links for all records in the model, I would like to use one edit link and then update it as items are selected in the dropdownlist. I have been able to achieve some of this using jquery , I would like to do it in C# code using MVC.
Any thoughts??
I created a Sample code. I have an area. Highlighted part is your concerned code.
Controller
public class DropdownController : Controller
{
[HttpGet]
public ActionResult DropDownListFor()
{
Practise.Areas.MyPractise.Models.Dropdown d = new Models.Dropdown();
return View(d);
}
public ActionResult Edit(string Val)
{
return View();
}
}
Model
public class Dropdown
{
[Required(ErrorMessage = "Please select state")]
public string StateId { get; set; }
public int MyProperty { get; set; }
public List<SelectListItem> States
{
get
{
return new List<SelectListItem>()
{
new SelectListItem
{
Text = "Punjab",
Value = "Pb",
Selected = false
},
new SelectListItem
{
Selected = false,
Value = "HM",
Text = "Himachal"
}
};
}
}
}
DropDownListFor View
#model Practise.Areas.MyPractise.Models.Dropdown
<!DOCTYPE html>
<html>
<head>
<title>DropDownListFor</title>
<script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#StateId').change(function () {
if($('#StateId option:selected').val() == "")
$('.edit').attr('href', "#");
else
$('.edit').attr('href',
"#Url.Action("Edit", "Dropdown",
new RouteValueDictionary(new { area = "MyPractise" }))"
+ "/" + $('#StateId option:selected').text());
});
});
</script>
</head>
<body>
#using (Html.BeginForm("DropDownListFor", "DropDown", FormMethod.Post,
new { id = "DropDownList" }))
{
#Html.DropDownListFor(m => m.StateId, Model.States, "select");
#Html.ValidationMessageFor(m => m.StateId);
<a class="edit" href="#">Edit</a>
<input type="submit" name="Submit" value="Submit" />
}
</body>
</html>
Area registration under MyPractiseAreaRegistration class under highlighted area
public class MyPractiseAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "MyPractise";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"MyPractise_default1",
"MyPractise/{controller}/{action}/{Val}",
new { action = "Index", Val = UrlParameter.Optional }
);
context.MapRoute(
"MyPractise_default",
"MyPractise/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
Related
I have two models, LoginModel and DatabaseModel. Combining them, I have created DatabaseCombinedWithOtherModel. The View, Login.cshtml is Strongly-Typed with the combined model. On running the Login.cshtml, the LoginModel returns null
I have all the necessary get and set methods
Here is the Controller class
namespace ReadingCat.Controllers
{
public class LoginController : Controller
{
private int userid;
// GET: Login
[HttpGet]
public ActionResult Login()
{
return View(new DatabaseCombinedWithOtherModel());
}
[HttpPost]
public ActionResult Login(DatabaseCombinedWithOtherModel model)
{
string realPassword = "";
string paswordFromUser = "";
string query = "SELECT password, userid FROM USERS WHERE username
= '" + model.loginModel.username + "'";
DataSet dataSet = model.databaseModel.selectFunction(query);
if (realPassword == paswordFromUser)
{
userid =
Convert.ToInt32(dataSet.Tables[0].Rows[0].ItemArray[1]);
model.loginModel.userid = userid;
return View("~/Views/Profile/Profile.cshtml",
model.loginModel);
}
else
return View();
}
}
}
Here is the Model:
namespace ReadingCat.Models
{
public class DatabaseCombinedWithOtherModel
{
public DatabaseModel databaseModel { get; set; }
public LoginModel loginModel { get; set; }
}
}
And here is the View:
#model ReadingCat.Models.DatabaseCombinedWithOtherModel
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Login</title>
<!-- Main css -->
<link rel="stylesheet" href="~/css/login.css">
</head>
<body>
<div class="login-page">
<div class="form">
<form class="register-form">
</form>
#using (Html.BeginForm("Login", "Login", FormMethod.Post))
{
<form class="login-form">
#Html.TextBox("Username", null, new { placeholder = "Username",
#class = "login.css" })
#Html.ValidationMessageFor(model => model.loginModel.username);
#Html.Password("Password", null, new { placeholder = "Password",
#class = "login.css" })
#Html.ValidationMessageFor(model => model.loginModel.password);
<div class="form-submit">
<button type="submit" value="Submit" class="submit"
id="submit" name="submit">Login</button>
</div>
<p class="message">Not registered? Create an account</p>
</form>
}
</div>
</div>
<img class="coffee-image" src="~/images/coffee.gif" alt="">
It is giving the following error
System.NullReferenceException: 'Object reference not set to an instance
of
an object.'
ReadingCat.Models.DatabaseCombinedWithOtherModel.loginModel.get returned
null.
I think this error about not fully declare DatabaseCombinedWithOtherModelthis model.
Please try this code.
private int userid
DatabaseCombinedWithOtherModel modelobj = new DatabaseCombinedWithOtherModel();
// GET: Login
[HttpGet]
public ActionResult Login()
{
return View(modelobj);
}
And also try this thing that before call the model in view firstly add some
values in objects from controller side pass return View(modelobj);and then call in view side.
Since you are not seting the loginmodel, it will be null Which will throw the exception.
Either initialize the loginModel in the otherModel's constructor or in the Login get action.
Try
namespace ReadingCat.Models
{
public class DatabaseCombinedWithOtherModel
{
public DatabaseModel databaseModel { get; set; }
public LoginModel loginModel { get; set; }
}
public DatabaseCombinedWithOtherModel()
{
loginModel = new LoginModel();
databaseModel = new DatabaseModel();
}
}
or
[HttpGet]
public ActionResult Login()
{
var vm = new DatabaseCombinedWithOtherModel()
vm.loginModel = new LoginModel();
vm.databaseModel = new DatabaseModel();
return View(vm);
}
The mentioned error goes away if #Html.Textbox is replaced with #Html.EditorFor. Then, another error arises with the DatabaseModel. It returns null. So I created a different object of DatabaseModel and worked with that.
I have a controller as shown below.
public ActionResult Index()
{
return View(db.FEE_TYPES.ToList());
}
By default it will render a View called Index. However, I have three views I want to Render
Index
Index2
Index3
I want to have three RadioButtons on the View
RadioButton1
RadioButton2
RadioButton3
When RadioButton1 is clicked, Render Index.
When RadioButton2 is clicked, Render Index2
When RadioButton3 is clicked, Render Index3
Please how do I achieve this?
I have Created a Demo from your Code Reference.
First i have create a Model with 3 properties in it.
Model
public class DemoModel
{
public string Radio1 { get; set; }
public string Radio2 { get; set; }
public string Radio3 { get; set; }
}
After creating a Model i have created a Controller with name RadioRenderController in that controller i have added 4 Action Method in that Index returns Main View.
And Remaining 3 Action Methods [ GetView1 , GetView2 , GetView3 ] return partial View.
Controller
using System.Web.Mvc;
using WebApplication6.Models;
namespace WebApplication6.Controllers
{
public class RadioRenderController : Controller
{
// GET: RadioRender
public ActionResult Index()
{
DemoModel DemoModel = new Models.DemoModel();
return View(DemoModel);
}
public ActionResult GetView1()
{
return PartialView("_DemoView1");
}
public ActionResult GetView2()
{
return PartialView("_DemoView2");
}
public ActionResult GetView3()
{
return PartialView("_DemoView3");
}
}
}
View
#model WebApplication6.Models.DemoModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
function GetView1() {
$("#viewPlaceHolder").load("/RadioRender/GetView1");
}
function GetView2() {
$("#viewPlaceHolder").load("/RadioRender/GetView2");
}
function GetView3() {
$("#viewPlaceHolder").load("/RadioRender/GetView3");
}
</script>
</head>
<body>
<div>
#Html.RadioButtonFor(m => m.Radio1, "1", new { #onclick = "GetView1();" }) Radio1
</div>
<div>
#Html.RadioButtonFor(m => m.Radio1, "2", new { #onclick = "GetView2();" }) Radio2
</div>
<div>
#Html.RadioButtonFor(m => m.Radio1, "3", new { #onclick = "GetView3();" }) Radio3
</div>
<div id="viewPlaceHolder"></div>
</body>
</html>
Partial Views
Output
I am using a WebGrid, which i bind to a List of objects containing information about deliveries. I want to be able to filter said WebGrid using a DropDownList containing Customers. When I select a Customer in the DropDownList the change-method sends an Ajax call which is supposed to get the new items for the WebGrid.
The call is successful, but nothing happens. The WebGrid doesn't change at all. I even tried sending an Ajax call identical to the ones sent when sorting the list. But nothing happens.
What am I doing wrong here?
ViewModel:
public class DeliveriesViewModel : PageViewModel<DeliveriesPage>
{
public DeliveriesViewModel(DeliveriesPage currentPage) : base(currentPage)
{
DeliveryItems = new List<DeliveryItem>();
}
public List<DeliveryItem> DeliveryItems { get; set; }
public List<SelectListItem> Customers { get; set; }
}
Controller:
public ActionResult Index(DeliveriesPage currentPage, string customer)
{
var model = new DeliveriesViewModel(currentPage);
model.Customers = _deliveryService.GetCustomers();
model.DeliveryItems = customer == null ? _deliveryService.GetDeliveryItems() : _deliveryService.GetDeliveryItems(customer);
return View(model);
}
View:
#model DeliveriesViewModel
<h1>#Model.CurrentPage.PageName</h1>
#Html.DropDownList("customerDropDown", Model.Customers)
#Html.Partial("_grid", Model)
<script type="text/javascript">
$("#customerDropDown").change(function () {
$.get("?Customer="+$("#customerDropDown").val());
});
</script>
_grid partial View:
#model DeliveriesViewModel
#{
var grid = new WebGrid(Model.DeliveryItems, canPage:true, canSort: true, ajaxUpdateContainerId:"container-grid");
}
<div id="container-grid">
#grid.GetHtml(
columns: grid.Columns(
grid.Column("DeliveryId"),
grid.Column("CustomerName"),
grid.Column("ShipNumber"),
grid.Column("ShipName"),
grid.Column("Product"),
grid.Column("PlannedWeight"),
grid.Column("TotalWeight"),
grid.Column("ShipStatus"),
grid.Column("TransportTo"),
grid.Column("TransportFrom"),
grid.Column("RevDate"),
grid.Column("ShipStemDept"),
grid.Column("ShipRealDept"),
grid.Column("ShipStemArr"),
grid.Column("ShipRealArr"),
grid.Column("TranspMonth"),
grid.Column("TranspYear")
))
</div>
$.get("?Customer="+$("#customerDropDown").val()); sends an AJAX call to the server and that's about it. You haven't subscribed to the success callback in order to update your DOM. So it is not surprising that nothing happens.
So try like this:
<script type="text/javascript">
$('#customerDropDown').change(function () {
var url = '#Url.Action("index")';
$.get(url, { customer: $(this).val() }, function(result) {
$('#container-grid').html(result);
});
});
</script>
Notice how I have used the UrlHelper to calculate the correct url to your controller action, I have then passed the selected value of the dropdown as second parameter to the $.get method and last but not least I have subscribed to the success callback of the ajax request and updated the #container-grid div with the results returned by the controller action.
Also since you are calling this action with AJAX, you should return only a PartialView from it and not an entire View. This partial view should contain your grid. Otherwise you will end up with duplicate layout injected into the div.
Model
public class EmployerTestResultsModel
{
[Display(Name = "Employer List")]
public IEnumerable<SelectListItem> EmployerList { get; set; }
[Required]
public string SelectedEmployerId { get; set; }
public List<EmployerTestResultsModel> EmployerGrid { get; set; }
public Int64 FileId { get; set; }
[Display(Name = "File Name")]
public string FileName { get; set; }
[DataType(DataType.Date)]
public DateTime Date { get; set; }
[Display(Name = "Scheme Id")]
public string SchemeId { get; set; }
public string Status { get; set; }
[Display(Name = "Validation Error Report")]
public string ValidationErrorReport { get; set; }
}
controller
[HttpGet]
public ActionResult EmployerTestResults()
{
EmployerTestResultsModel model = new EmployerTestResultsModel();
ViewBag.HideSection = true;
model.EmployerList = (from d in _context.Employers
select new System.Web.Mvc.SelectListItem
{
Text = d.EmployerName,
Value = d.EmployerId
});
model.EmployerGrid = (from efd in _context.EmployerFileDatas
// join efhd in _context.EmployerFileHeaderDetails on efd.FileDataIdentityKey equals efhd.FileDataIdentityKey
orderby efd.EmployerId , efd.Timestamp
select new EmployerTestResultsModel
{
FileId = efd.FileDataIdentityKey,
FileName = efd.FileName,
Date = efd.Timestamp,
//SchemeId = efhd.SchemeId,
Status = efd.ValidationStatus,
ValidationErrorReport = "View"
}).ToList();
return View("EmployerTestResults", model);
}
View:
#model EFITestHarness.Models.EmployerTestResultsModel
#using System.Web.Helpers;
#{
ViewBag.Title = "EmployerTestResults";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#using (Html.BeginForm("EmployerTestResults", "Home", FormMethod.Post, new { #class = "form-horizontal" }))
{
<div class="text-danger" style="font-size:large;">
#Html.ValidationSummary(true)
</div>
<div class="form-group ">
#Html.LabelFor(s => s.EmployerList, null, new { #class = "col-md-2 control-label" })
<div class="col-md-3">
#Html.DropDownListFor(s => s.SelectedEmployerId, Model.EmployerList, "----All----", new { style = "width:250px", id = "ddl", #class = "dropdown1" })
#Html.ValidationMessageFor(s => s.EmployerList, null, new { #class = "text-danger" })
</div>
</div>
<div id="EmployeeViewGrid">
#Html.Partial("~/Views/EmployerView.cshtml", Model.EmployerGrid)
</div>
}
<script type="text/javascript">
$('#ddl').change(function (e) {
var employer = $('#ddl').val();
$.get('#Url.Action("Filter")', { id: employer }, function (result) {
$('#EmployeeViewGrid').html(result);
});
e.preventDefault();
});
</script>
Controller:
[HttpGet]
public ActionResult Filter(string id)
{
EmployerTestResultsModel model = new EmployerTestResultsModel();
List<EmployerTestResultsModel> objEmployerDetails = new List<EmployerTestResultsModel>();
objEmployerDetails = _repository.getEmployerDetails(id);
model.EmployerGrid = objEmployerDetails;
return PartialView("~/Views/EmployerView.cshtml", model.EmployerGrid);
}
partial View:
#model IEnumerable<EFITestHarness.Models.EmployerTestResultsModel>
#using System.Web.Helpers;
#{
ViewBag.Title = "EmployerTestResultsModel";
//Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-1.7.1.js"></script>
<div id="gridposition" style="overflow: scroll; height: 300px; overflow-x: hidden;">
#{
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridposition"); grid.Pager(WebGridPagerModes.NextPrevious);
#grid.GetHtml(tableStyle: "webGrid",
footerStyle: "foot",
headerStyle: "webGridHeader",
alternatingRowStyle: "webGridAlt",
htmlAttributes: new { id = "positionGrid" },
selectedRowStyle: "select",
fillEmptyRows: true,
columns: grid.Columns(
grid.Column("FileName"), //the model fields to display
grid.Column("Date"),
grid.Column("SchemeId"),
grid.Column("Status"),
grid.Column("ValidationErrorReport", format: (item => Html.ActionLink((string)(#item.ValidationErrorReport).ToString(), "EmployerValidationResults", new { FileId = #item.FileId, #style = "color:blue;" })))
))
}
</div>
I have a form in MVC 4 which contains several fields and, depending on the value of a combo, I need to open a modal dialog form and load into that one 3 additional fields that will impact against the same entity that I'm creating/editing in the main form.
For this modal dialog I'm using the one from jQuery UI.
Now, what I need to do is to validate (Required) the fields within the modal dialog in order to allow the user to retain the entered values which will be submited later by the main form.
My problem is how to perform the validation of those 3 fields from within the modal form (because they wouldn't be able to submit the main form until dialog is closed).
Any hints or ideas?
Regards,
Cesar.
You could use AJAX to submit the form modal to the server. The modal form will have of course a separate view model associated with it. Let's exemplify:
Main view model:
public class MyViewModel
{
[DisplayName("select a value")]
public string SelectedValue { get; set; }
public IEnumerable<SelectListItem> Values { get; set; }
public string SomeOtherProperty { get; set; }
}
Modal dialog view model:
public class DialogViewModel
{
[Required]
public string Prop1 { get; set; }
[Required]
public string Prop2 { get; set; }
[Required]
public string Prop3 { get; set; }
}
Then you could have a controller containing 4 actions:
public class HomeController : Controller
{
// Renders the main form
public ActionResult Index()
{
var model = new MyViewModel
{
Values = new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
}
};
return View(model);
}
// Processes the submission of the main form
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return Content(
string.Format(
"Thanks for filling out the form. You selected value: \"{0}\" and other property: \"{1}\"",
model.SelectedValue,
model.SomeOtherProperty
)
);
}
// Renders the partial view which will be shown in a modal
public ActionResult Modal(string selectedValue)
{
var model = new DialogViewModel
{
Prop1 = selectedValue
};
return PartialView(model);
}
// Processes the submission of the modal
[HttpPost]
public ActionResult Modal(DialogViewModel model)
{
if (ModelState.IsValid)
{
// validation of the modal view model succeeded =>
// we return a JSON result containing some precalculated value
return Json(new
{
value = string.Format("{0} - {1} - {2}", model.Prop1, model.Prop2, model.Prop3)
});
}
// Validation failed => we need to redisplay the modal form
// and give the user the possibility to fix his errors
return PartialView(model);
}
}
Next you could have a main view (~/Views/Home/Index.cshtml):
#model MyViewModel
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(x => x.SelectedValue)
#Html.DropDownListFor(x => x.SelectedValue, Model.Values, new { id = "ddl" })
</div>
<div>
#Html.LabelFor(x => x.SomeOtherProperty)
#Html.TextBoxFor(x => x.SomeOtherProperty, new { id = "otherProperty" })
#Html.ActionLink(
"click here to open a modal and help you fill the value",
"Modal",
"Home",
null,
new { id = "showModal" }
)
</div>
<button type="submit">OK</button>
}
<div id="modal"></div>
and a partial view to contain the modal form (~/Views/Home/Modal.cshtml):
#model DialogViewModel
#using (Ajax.BeginForm(new AjaxOptions { OnSuccess = "handleModalSubmit" }))
{
<div>
#Html.LabelFor(x => x.Prop1)
#Html.EditorFor(x => x.Prop1)
#Html.ValidationMessageFor(x => x.Prop1)
</div>
<div>
#Html.LabelFor(x => x.Prop2)
#Html.EditorFor(x => x.Prop2)
#Html.ValidationMessageFor(x => x.Prop2)
</div>
<div>
#Html.LabelFor(x => x.Prop3)
#Html.EditorFor(x => x.Prop3)
#Html.ValidationMessageFor(x => x.Prop3)
</div>
<button type="submit">OK</button>
}
OK, now all that's left is write some javascript to make the whole thing alive. We start by making sure that we have included all the required scripts first:
<script src="#Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
and then write our own:
$(function () {
$('#showModal').click(function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
data: { selectedValue: $('#ddl').val() },
success: function (result) {
$('#modal').html(result).dialog('open');
}
});
return false;
});
$('#modal').dialog({
autoOpen: false,
modal: true
});
});
function handleModalSubmit(result) {
if (result.value) {
// JSON returned => validation succeeded =>
// close the modal and update some property on the main form
$('#modal').dialog('close');
$('#otherProperty').val(result.value);
} else {
// validation failed => refresh the modal to display the errors
$('#modal').html(result);
}
}
In my application I have associated my UserId to a table in my database. I need that when I create a new item I can choose the user name from a dropdownlist. And 'possible to do this with the element viewbag?
#Html.EditorFor(model => model.UserId)
I use default membership provider so I can't use Entity Framework for this problem
EDIT
EDIT 2
This is my action create:
[HttpPost]
public ActionResult Create(Employe employe)
{
var users = Roles.GetUsersInRole("Admin");
SelectList list = new SelectList(users);
ViewBag.Users = list;
if (ModelState.IsValid)
{
**employe.EmployeID = users;**
db.Employes.Add(employe);
db.SaveChanges();
}
This does not work. The error is:
Cannot implicitly convert type 'string[]' to 'string'
My model for Employee
public class Employee
{
[Key]
public int EmployeID { get; set; }
public Guid UserId { get; set; }
public string Name { get; set; }
[ForeignKey("UserId")]
public virtual MembershipUser User
{
get
{
return Membership.GetUser(this.Name); //Changed this to Name
}
}
}
}
View:
#Html.DropDownList("Users", ViewBag.Users as SelectList);
My result in UserId field isn't a UserId but this 000000-000000-0000000-00000
How to set a list of users as a SelectItem in the ViewBack
Yes, you should be able to do this by passing your collection to the ViewBag and then create you dropdown from it:
In your controller
var users = Roles.GetUsersInRole("Admin");
SelectList list = new SelectList(users);
ViewBag.Users = list;
In your View (If you're using Razor)
#Html.DropDownList("Users", ViewBag.Users as SelectList);
Read more about SelectListItem here:
http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem.aspx
Also check out:
How can I get this ASP.NET MVC SelectList to work?
Problem with ASP.Net MVC SelectLIst and List<SelectListItems>
Question changed to something more. Here is my idea to solve the issue:
Controller:
public ActionResult Mirko() {
List<SelectListItem> items = new List<SelectListItem>();
foreach (string userName in Roles.GetUsersInRole("Admin")) {
var user = Membership.GetUser(userName);
SelectListItem li = new SelectListItem {
Value = user.ProviderUserKey.ToString(),
Text = user.UserName,
};
items.Add(li);
}
items.Add(new SelectListItem { Text = "Please Select...", Value = "na" , Selected = true});
ViewBag.Users = items;
return View();
}
[HttpPost]
public ActionResult Mirko(Employee employee) {
if(IsValideEmployee(employee)) {
/*Only used to show that user was retrieved*/
TempData["message"] = "Saved Employee";
TempData["user"] = employee.User;
/* employeeRepository.Save(employee) */
/* Redirect to where you want to go */
return RedirectToAction("Mirko", "Home");
}
return View(employee);
}
private bool IsValideEmployee(Employee emp) {
if (emp.Name == "na")
ModelState.AddModelError("UserId", "You must select a user!");
/*Do some validation here*/
//ModelState.Add("Name", "You must set the user name!")
return ModelState.IsValid;
}
View
#model StackOverFlowExample.Models.Employee
#{
MembershipUser user = null;
ViewBag.Title = "Mirko Example";
var users = ViewBag.Users as IEnumerable<SelectListItem>;
}
#if (TempData["message"] != null) {
user = TempData["user"] as MembershipUser;
<h3>#TempData["message"]</h3>
<div>
<span>You selected #user.UserName</span>
<ul>
<li>Email: #user.Email</li>
<li>Last Logged In: #user.LastLoginDate.ToString("d")</li>
<li>Online: #user.IsOnline</li>
</ul>
</div>
}
#using (#Html.BeginForm()) {
<label for="UserId">Associate Employee To User:</label>
#Html.DropDownListFor(m => m.UserId, #users)
#Html.HiddenFor(m => m.Name)
<input type="submit" value="Save" id="save-employee"/>
}
<div id="status" style="display:none;"></div>
<script type="text/javascript">
$(document).ready(function () {
$("#UserId").change(function () {
//Set value of name
$("#Name").val($(this).children("option:selected").text());
});
$("#save-employee").click(function (e) {
var value = $("#Name").val();
if (value == "" || value == "na") {
e.preventDefault();
$("#status").html("<h3>You must select a user!</h3>").toggle();
}
});
});
</script>