Set the textbox value using the controller ASP.NET MVC 4 - asp.net-mvc

Is it possible to set the value of the textbox using the controller? I have the following form in my View:
#Html.TextBoxFor(Models => Models.techNo, new { #class="form-control maintain-text",
placeholder="Technician No..."})
<button type="submit" id="search" name="SubmitButton" value="search" class="btn btn-default">Search</button>
<td>First Name :</td>
<td>#Html.TextBoxFor(Models => Models.firstName, new { #class = "form-control", style = "width:380px;", disabled = "disabled" })</td>
<td>Last Name :</td>
<td>#Html.TextBoxFor(Models => Models.lastName, new { #class = "form-control", style = "width:380px;", disabled = "disabled" })</td>
Model:
public string techNo { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
Controller:
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult ProcessTech(string SubmitButton)
{
TechnicianFacade _oTechFacade = new TechnicianFacade();
Technician _oTechnician = new Technician();
string fName = Request.Form["firstName"].ToString().ToUpper();
string lName = Request.Form["lastName"].ToString().ToUpper();
switch (SubmitButton)
{
case "save": //add new technician
{
}
break;
case "update": //update technician details
{
}
break;
case "search": //search technician
{
try {
string id = Request.Form["techNo"].ToString().ToUpper();
if (isValid(id, "technician") == false) //search the id from the database
{
//do nothing
}
else //if id is valid
{
var tech = _oTechFacade.getTechnicians(id, _oAppSetting.ConnectionString)[0]; //data from the database
string fNameStr = tech.GetType().GetProperty("FIRSTNAME").GetValue(tech, null).ToString();
string lNameStr = tech.GetType().GetProperty("LASTNAME").GetValue(tech, null).ToString();
//When the the ID is found,
//these are the values of the firstName & lastName that I want to set to the View
//Is it possible to set the values of the textboxes from here?
}
}
catch (Exception ex) { throw ex; }
}
break;
case "delete":
{
}
break;
}
return View("Index");
}
Basically, after searching the ID(assuming its valid) I want to grab the firstName & lastName data from the database and then display it to the View for updating or deleting. I've tried ViewBag, ViewData, and TempData but all are not working for me.
EDIT:
#model Maintenance_.Models.IndexModel
#{
ViewBag.Title = "Technician";
}
<div id="page-wrapper">
<div class = "row">
<div class = "col-lg-12">
<h1 class= "page-header"> Technician </h1>
</div>
</div>
....

As i see your code, you are using explicitly typed view and using same view for insert and update. And in this case you must return model to your view like that:
[HttpPost]
public ActionResult ProcessTech(string SubmitButton)
{
TechnicianFacade _oTechFacade = new TechnicianFacade();
Technician _oTechnician = new Technician();
string fName = Request.Form["firstName"].ToString().ToUpper();
string lName = Request.Form["lastName"].ToString().ToUpper();
YourModelName model = new YourModelName ();
switch (SubmitButton)
{
case "save": //add new technician
{
}
break;
case "update": //update technician details
{
}
break;
case "search": //search technician
{
try {
string id = Request.Form["techNo"].ToString().ToUpper();
if (isValid(id, "technician") == false) //search the id from the database
{
//do nothing
}
else //if id is valid
{
var tech = _oTechFacade.getTechnicians(id, _oAppSetting.ConnectionString)[0]; //data from the database
string fNameStr = tech.GetType().GetProperty("FIRSTNAME").GetValue(tech, null).ToString();
string lNameStr = tech.GetType().GetProperty("LASTNAME").GetValue(tech, null).ToString();
model.firstname = fNameStr;
model.lastname = lNameStr;
//When the the ID is found,
//these are the values of the firstName & lastName that I want to set to the View
//Is it possible to set the values of the textboxes from here?
}
}
catch (Exception ex) { throw ex; }
}
break;
case "delete":
{
}
break;
}
return View("Index",model);
}

This line:
return View("Index");
is not passing a model to the Index view.
You need to create an instance of your view, and set its properties:
var model = new IndexModel();
...
else //if id is valid
{
var tech = _oTechFacade.getTechnicians(id, _oAppSetting.ConnectionString)[0]; //data from the database
string fNameStr = tech.GetType().GetProperty("FIRSTNAME").GetValue(tech, null).ToString();
string lNameStr = tech.GetType().GetProperty("LASTNAME").GetValue(tech, null).ToString();
//When the the ID is found, we populate our model
//so it can be displayed
model.firstname = fNameStr;
model.lastname = lNameStr;
}
Now you can do:
return View("Index", model);

#Brendan Green answer is correct you need pass model to the view Also then you can set text box value using add new property to Html Helper.
#Html.TextBoxFor(Models => Models.firstName, new { #class = "form-control", style = "width:380px;", disabled = "disabled", #value = Model.firstName })
Note here value set by #value property
Update:
Change < button > element to < input type="submit" > also change the id to SubmitButton and Name also SubmitButton (id and Name values same is good)then try again seems to problem with your switch statement. Debug it then you can see what happen.
Also pass model to view and Name of the View should be Index then view correctly calling.

Related

Asp .Net MVC, how to put/include values to DropDownListFor?

I am following this tutorial which works very fine. But the problem is that it only provides key and without it own value (As shown in the picture below). How to include values to each of these keys?
Inspected Elements (Picture)
Model
[Required( ErrorMessage = "Selection is a MUST" )]
public string SelectedItem { get; set; }
private List<string> _items;
public List<string> Items
{
get
{
_items = new List<string>();
_items.Add("One");
_items.Add("Two");
_items.Add("Three");
return _items;
}
}
Controller
public class HomeController : Controller
{
//Render Action
[HttpGet]
public ViewResult Index()
{
DropdownListModel model = new DropdownListModel();
return View(model);
}
//Process Action
[HttpPost]
public ViewResult Index(DropdownListModel model)
{
//TODO: Validate using if(ModelState.IsValid) and process information
return View(model);
}
}
View
<div>
<!--Render the DropDownListmodel -->
#using (Html.BeginForm())
{
<p>#Html.ValidationSummary()</p>
<p>Select an Item : #Html.DropDownListFor(x => x.SelectedItem, new SelectList(Model.Items), "--Choose any Item--" )</p>
<input type="submit" value="Submit" />
}
<!-- Display Selected Item -->
#if (!String.IsNullOrWhiteSpace(Model.SelectedItem))
{
<span>Selected Item : #Model.SelectedItem</span>
}
</div>
What I Attempted
I replaced the codes in models with the code below. But I have error saying Models.KeyValueModel: : EntityType 'KeyValueModel' has no key defined. Define the key for this EntityType.
KeyValueModels: EntityType: EntitySet 'KeyValueModels' is based on type 'KeyValueModel' that has no keys defined.
public List<KeyValueModel> Items
{
get
{
List<KeyValueModel> item = new List<KeyValueModel>();
var n = new KeyValueModel();
n.Key = "1";
n.Value = "One";
item.Add(n);
n = new KeyValueModel();
n.Key = "2";
n.Value = "Second";
item.Add(n);
n = new KeyValueModel();
n.Key = "3";
n.Value = "Three";
item.Add(n);
return item;
}
}
You need to specify on your HttpGet request your Key Value pair like this one:
DropdownListModel model = new DropdownListModel();
model.ItemList = new List<SelectListItem>()
{
new SelectListItem { Text = "One", Value = "1" },
new SelectListItem { Text = "Two", Value = "2" }
};
Then on your model, add this:
public IEnumerable<SelectListItem> ItemList { get; set; }
And on your View:
#Html.DropDownListFor(x => x.SelectedItem, Model.Items, "--Choose any Item--" )
add the Model as:
public string nameofdropdown{ get; set; }
public IEnumerable<SelectListItem> listyouwanttodisplay{ get; set; }
In get method:
Model model=new Model;
List<SelectListItem> cd = Get() //call here----
var additionaldata= new SelectListItem()
{
Value = null,
Text = "--- place holder---"
};
cd.Insert(0, additionaldata);
model.listyouwanttodisplay=cd;
return View (model);
In View:
<div>
#Html.DropDownListFor(model => model.nameofdropdown, new
SelectList(Model.listyouwanttodisplay, "Value","Text"),htmlAttributes: new { #class = "form-control" })
</div>

Passing Model data from View to Controller

I am trying to pass the Model data from a View (and PartialView within the View) back to the Controller upon HttpPost. (Adapted from Pass SelectedValue of DropDownList in Html.BeginForm() in ASP.NEt MVC 3)
Why? I want to show a list of assets each with a DropDownList and number of options. Upon submission of form to read the selected items from DropDownList.
My 2 (simplified) models:
public class Booking
{
public int BookingID { get; set; }
public int StoreID { get; set; }
...
public IEnumerable<AssetShort> Assets { get; set; }
}
and
public class AssetShort
{
public int AssetID { get; set; }
....
public int SelectedAction { get; set; }
public IEnumerable<SelectListItem> ActionList { get; set; }
}
In my Booking Controller > Create I build the List:
public ActionResult Booking(int id)
{
// get myBag which contains a List<Asset>
// booking corresponds to 'id'
var myAssets = new List<AssetShort>();
foreach (var a in myBag.Assets)
{
var b = new AssetShort();
b.AssetID = a.ID;
b.SelectedAction = 0;
b.ActionList = new[]
{
new SelectListItem { Selected = true, Value = "0", Text = "Select..."},
new SelectListItem { Selected = false, Value = "1", Text = "Add"},
new SelectListItem { Selected = false, Value = "2", Text = "Remove"},
new SelectListItem { Selected = false, Value = "3", Text = "Relocate"},
new SelectListItem { Selected = false, Value = "4", Text = "Upgrade"},
new SelectListItem { Selected = false, Value = "5", Text = "Downgrade"}
};
myAssets.Add(b);
};
var model = new BookingRequirementsViewModel
{
BookingID = booking.ID,
StoreID = booking.StoreID,
Assets = myAssets.ToList(),
};
return View(model);
My View:
#model uatlab.ViewModels.BookingRequirementsViewModel
#{
ViewBag.Title = "Booking step 2";
}
<h4>Your booking ref. #Model.BookingID</h4>
#using (Html.BeginForm("Booking2", "Booking", FormMethod.Post))
{
<fieldset>
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.StoreID)
#Html.Partial("_Assets", Model.StoreAssets)
<input type="submit" value="Cancel" class="btn btn-default" />
<input type="submit" value="Next" class="btn btn-default" />
</fieldset>
}
The Partial View includes
#foreach (var item in Model)
{
<tr>
<td>#item.Name</td>
<td>#item.Number</td>
<td>#Html.DropDownListFor(modelItem=>item.SelectedAction, item.ActionList)</td>
</tr>
}
So, all this works fine in the browser and I can select dropdowns for each asset listed but when I submit the only value posted back is the StoreID as it is in a "HiddenFor".
The booking2 controller has the model for a parameter:
public ActionResult Booking2(BookingRequirementsViewModel model)
{
//loop through model.Assets and display SelectedActions
}
Let me make it clear what the problems is - in Booking2 controller the Model is null when viewed in Debug mode and I get error "Object reference not set to an instance of an object."
Any ideas please how to pass back the Model to controller from view?
Regards
Craig
You need to create an EditorTemplate for AssetShort. I also suggest moving ActionList to the BookingRequirementsViewModel so your not regenerating a new SelectList for each AssetShort
The models you have posted aren't making sense. Your controller has var model = new BookingRequirementsViewModel { ..., Assets = myAssets.ToList() }; but in the view you refer to #Html.Partial("_Assets", Model.StoreAssets)? Are these 2 different properties. I will assume that StoreAssets is IEnumerable<AssetShort>
/Views/Shared/EditorTemplates/AssetShort.cshtml
#model AssetShort
<tr>
<td>#Html.DispayFor(m => m.Name)</td>
....
<td>
#Html.DropDownListFor(m => m.SelectedAction, (IEnumerable<SelectListItem>)ViewData["actionList"], "--Please select--")
#Html.ValidationMessageFor(m => m.SelectedAction)
</td>
</tr>
In the main view
#model uatlab.ViewModels.BookingRequirementsViewModel
....
#using (Html.BeginForm()) // Not sure why you post to a method with a different name
{
....
#Html.HiddenFor(m => m.StoreID)
#Html.EditorFor(m => m.StoreAssets, new { actionList = Model.ActionList })
....
}
In the controller
public ActionResult Booking(int id)
{
....
var model = new BookingRequirementsViewModel
{
BookingID = booking.ID,
StoreID = booking.StoreID,
Assets = myBag.Assets.Select(a => new AssetShort()
{
AssetID = a.ID,
SelectedAction = a.SelectedAction, // assign this if you want a selected option, otherwise the "--Please select--" option will be selected
....
})
};
ConfigureViewModel(model); // Assign select list
return View(model);
}
And a separate method to generate the SelectList because it needs to be called in the GET method and again in the POST method if you return the view. Note use the overload of DropDownListFor() to generate the option label (null value) as above, and there is no point setting the Selected property (the value of SelectedAction determines what is selected, not this)
private ConfigureViewModel(BookingRequirementsViewModel model)
{
model.ActionList = new[]
{
new SelectListItem { Value = "1", Text = "Add"},
....
new SelectListItem { Value = "5", Text = "Downgrade"}
};
}
and the POST
public ActionResult Booking(BookingRequirementsViewModel model)
{
if (!ModelState.IsValid)
{
ConfigureViewModel(model); // Re-assign select list
return View(model);
}
// save and redirect
}
I recommend also making SelectedAction nullable with the [Required] attribute so you get client and server side validation
public class AssetShort
{
public int AssetID { get; set; }
....
[Required]
public int? SelectedAction { get; set; }
}

Html.BeginForm POST overwrites image data when new image is not specified?

This is my first post to StackOverflow. I hope this is useful.
I have a Razor view that is intended to allow editing of the displayable properties of a model containing either pre-defined values or null values. The view should not change the contents of the model's properties unless the user changes them intentionally by editing them on in the UI based on the view. The view behaves correctly, except with regard to a property of type byte[] that contains image data: Model.ImageData
#using (Html.BeginForm("Edit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" } ))
{
#Html.EditorForModel()
<div class="editor-label">Image</div>
<div class="editor-field">
#if (Model.ImageData == null)
{
#: No image has been assigned in the database.
}
else
{
<img width="150" height="150" src="#Url.Action("GetImage", "Product", new { Model.ID} )" />
}
<div>Upload new image: <input type="file" name="Image" /></div>
</div>
<input type="submit" value="Save" />
}
The above view works as intended for all properties in the model except Model.ImageData. In this case, posting causes any previously set Model.ImageData to be set to null. I have confirmed that the Model.ImageData is set to null during post by verifying that prior to posting, Model.ImageData contains a valid byte array (with the expected image).
The controller code for the above view is:
public ViewResult Edit(int id)
{
Product product = repository.Products.FirstOrDefault(p => p.ID == id);
// breakpoint here shows that all model properties including product.ImageData are populated and valid.
return View(product);
}
[HttpPost]
public ActionResult Edit(Product product, HttpPostedFileBase Image)
{
if (ModelState.IsValid)
{
// breakpoint here shows that product.ImageData is null (but all other model properties are still populated with data).
if (Image != null)
{
product.ImageMimeType = Image.ContentType;
product.ImageData = new byte[Image.ContentLength];
Image.InputStream.Read(product.ImageData, 0, Image.ContentLength);
}
repository.SaveProduct(product);
TempData["Message"] = string.Format("{0} has been saved", product.Name);
return RedirectToAction("Index");
}
else
{
return View(product);
}
}
And here is the respository code that updates the model (though the model is changing before this code is called):
public void SaveProduct(Product product)
{
if (product.ID == 0)
{
context.Products.Add(product); // why doesn't this try to save ID = 0 to the ID field of the product in the database??
}
else
{
Product dbEntry = context.Products.Find(product.ID);
if (dbEntry != null)
{
dbEntry.Name = product.Name;
dbEntry.Description = product.Description;
dbEntry.Category = product.Category;
dbEntry.Price = product.Price;
dbEntry.ImageData = product.ImageData;
dbEntry.ImageMimeType = product.ImageMimeType;
}
}
context.SaveChanges();
}
What am I doing wrong?
This is really where you should consider using a ViewModel class instead. But to keep your current ways of doing things with minimal changes, try modifying the SaveProduct() method to the following:
public void SaveProduct(Product product, bool updateImage = false)
{
context.Products.Attach(product);
// mark product as modified
var entry = context.Entry(product);
entry.State = EntityState.Modified;
entry.Property(e => e.ImageData).IsModified = updateImage;
entry.Property(e => e.ImageMimeType).IsModified = updateImage;
context.SaveChanges();
}
and modify the controller code to:
...
var updateImage = false;
if (Image != null)
{
updateImage = true;
product.ImageMimeType = Image.ContentType;
product.ImageData = new byte[Image.ContentLength];
Image.InputStream.Read(product.ImageData, 0, Image.ContentLength);
}
repository.SaveProduct(product, updateImage);
....

ASP.NET MVC3 HtmlPasswordFor how to make it not reset after post methods

Essentially I have a HtmlPasswordFor(m => EmployeeID), I have a button called "Go". Once I hit the Go textbox, I actually do not want the password to disappear on the or have the field password to be cleared.
How would I do this?
BEFORE
AFTER
I do not want the my employeeid to reset. I want to keep the passwords in ****'s, but I'll need the password on my next post call.
Controller
[HttpGet]
public ActionResult MainForm()
{
var model = new VTViewModel();
return View(model);
}
[HttpPost]
public ActionResult MainForm(VTViewModel model, string buttontype)
{
if (ModelState.IsValid)
{
string EmployeeID = (Convert.ToInt64(model.EmployeeBinaryID, 2)).ToString();
if (buttontype == "Go")
{
// GET Fields depending on the serial number.
model.ListFields = logic_model.getFormInfo(model.SerialNumber, EmployeeID);
if (model.ListFields[0].return_num == "0")
{
model.Go = true;
// Set Process
// Set Header Token
// Set Header Title
ViewData["HEADER"] = model.ListFields[0].HeaderName + " | " + model.ListFields[0].TubeType + " | " + model.ListFields[0].ProductLine;
}
else
{
model.DisplayMessage = helper.checkErrors(model.ListFields[0].return_num);
}
}
else if (buttontype == "Submit")
{
model.HeaderToken = model.ListFields[0].HeaderToken;
string header = model.HeaderToken;
string check = "";
string return_num = model.ListFields[0].return_num;
// If the submission worked
//SUBMIT HERE INTO DB then Clear
List<string> values_to_submit = new List<string>(); // Creates a list to store the values to submit
for (int i = 0; i < model.ListFields.Count; i++)
{
// Fills in the hidden values.
if (model.ListFields[i].isHidden)
{
if (model.ListFields[i].Token == "SNT" || model.ListFields[i].Token == "SNC")
{
model.ListFields[i].Value = model.SerialNumber;
}
else if (model.ListFields[i].Token == "USR")
{
model.ListFields[i].Value = EmployeeID;
}
else if (model.ListFields[i].Token == "TMS")
{
model.ListFields[i].Value = "0";
}
}
// If it is a check box do the right conversion.
if (model.ListFields[i].DataType == "DATA-CKBOX")
{
//string convertedValue = helper.trueFalseStringtToIntBool(model.ListFields[i].Value);
string convertedValue = helper.boolToInt(model.ListFields[i].BoolValue).ToString();
model.ListFields[i].Value = convertedValue;
}
values_to_submit.Add(model.ListFields[i].Token + model.ListFields[i].Value);
}
check = logic_model.helperSubmit(values_to_submit, header, 1);
if (check == "Submitted")
{
ModelState.Clear();
VTViewModel clear_model = new VTViewModel(); // Creates an empty model
clear_model.DisplayMessage = "Submitted\n" + model.SerialNumber + "\n" + DateTime.Now;
return View(clear_model);
}
else
{
model.DisplayMessage = check; // Sets the display message to the error.
}
}
else if (buttontype == "Clear")
{
// Clears the screen and model
ModelState.Clear();
VTViewModel clear_model = new VTViewModel(); // Creates an empty model
return View(clear_model);
}
}
return View(model);
}
View
div>
<fieldset>
<table id="main_table">
<tr>
<td>#Html.LabelFor(m => m.SerialNumber)</td>
<td>#Html.LabelFor(m => m.EmployeeBinaryID)</td>
</tr>
<tr>
<td>#Html.TextBoxFor(m => m.SerialNumber)</td>
<td>#Html.PasswordFor(m => m.EmployeeBinaryID, new { autocomplete = "off" }) </td>
</tr>
<tr><td><input type="submit" value="Go" name="buttontype" class="submit_button" id="btn"/><br /><br /></td></tr>
</table>
</fieldset>
<br />
Thanks
Html.PasswordFor will never render the value, probably for security reasons. You can work around this, but you have to use Html.EditorFor instead, decorate the EmployeeID property with [DataType(DataType.Password)] and add the following editor template at ~/Views/Shared/EditorTemplates/Password.cshtml
#Html.Password("", ViewData.TemplateInfo.FormattedModelValue, new { #class = "text-box single-line password" })
You could also use [UIHint] and create a template for that particular property only.

ASP.NET MVC 3 Dropdownlist of Users

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>

Resources