here is my jquery :
$(document).ready(function () {
$("#GameId").change(function () {
$.get('/MatchManager/GetMatchType/' + $(this).val(), function (response) {
var Games = $.evalJSON(response);
var ddlSelectedProduct = $("#MatchTypeId");
$("#MatchTypeId > option").remove();
for (i = 0; i < Games.length; i++) {
ddlSelectedProduct.append($("<option />").val(Games[i].Value).text(Games[i].Text));
}
});
});
});
I print out the response and its correct, but for some reason my program stops at the $.evalJson and says $.evalJSON is not a function Here is my GetMatchType controller just in case:
public string GetMatchType(int id)
{
var ListMatchTypes = new List<SelectListItem>();
using (var db = new MatchGamingEntities())
{
var MyMatchTypes = from m in db.MatchTypes
where m.GameId == id
select m;
foreach (var item in MyMatchTypes.ToList())
{
ListMatchTypes.Add(new SelectListItem() { Text = item.MatchTypeName, Value = item.MatchTypeId.ToString() });
}
}
return new JavaScriptSerializer().Serialize(ListMatchTypes);
}
This is my view:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
MatchModel
#Html.LabelFor(model => model.GameId)
#Html.DropDownList("GameId", new SelectList(ViewBag.MyGames as System.Collections.IEnumerable, "GameId", "GameName"), "Please Select One")
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MatchTypeId)
</div>
<div class="editor-field">
#Html.DropDownList("MatchTypeId", new SelectList(ViewBag.MatchTypes as System.Collections.IEnumerable, "Value", "Text"))
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MatchName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MatchName)
#Html.ValidationMessageFor(model => model.MatchName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MatchDescription)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MatchDescription)
#Html.ValidationMessageFor(model => model.MatchDescription)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Wager)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Wager)
#Html.ValidationMessageFor(model => model.Wager) <br />
<span>Your Current Account Balance: #ViewBag.Balance</span>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
#Html.ActionLink("Back to List", "Index")
Remarks:
Controller actions should always return ActionResults
Use JsonResult instead of manually serializing with JavaScriptSerializer
You don't need to manually parse with any $.evalJSON on the client => if you followed my previous remark the proper content type application/json will be sent and jQuery will automatically parse the object passed to the success callback.
Never hardocode urls in your javascript => always use url helpers when dealing with urls or your code might break when you deploy due to virtual directory added.
This being said let's try to improve your code starting with the controller action:
public ActionResult GetMatchType(int id)
{
using (var db = new MatchGamingEntities())
{
return Json(
from m in db.MatchTypes
where m.GameId == id
select new {
Text = m.MatchTypeName,
Value = m.MatchTypeId
},
JsonRequestBehavior.AllowGet
);
}
}
and then the javascript:
$(function () {
$('#GameId').change(function () {
var url = '#Url.Action("GetMatchType", "MatchManager")';
var data = { id: $(this).val() };
$.get(url, data, function (games) {
var ddlSelectedProduct = $('#MatchTypeId');
ddlSelectedProduct.empty();
$.each(games, function(index, game) {
ddlSelectedProduct.append(
$('<option/>', {
value: game.Value,
text: game.Text
})
);
});
});
});
});
Instead of trying to parse the JSON yourself, let jQuery handle it.
Just replace your $.get with $.getJSON
jQuery will then automatically try to decode the response as JSON and you can automatically access it like a plain object.
jQuery.getJSON on the docs.
Did you include http://code.google.com/p/jquery-json/ ?
$(document).ready(function () {
$("#GameId").change(function () {
$.getJSON('/MatchManager/GetMatchType/' + $(this).val(), function (Games) {
var ddlSelectedProduct = $("#MatchTypeId");
$("#MatchTypeId > option").remove();
for (i = 0; i < Games.length; i++) {
ddlSelectedProduct.append($("<option />").val(Games[i].Value).text(Games[i].Text));
}
});
});
});
Related
Here is my code.
<div class="editor-label">
#Html.LabelFor(model => model.Branch)
</div>
<div class="editor-field">
#{ Booking_Program.Models.Booking_DB_Entities db = new Booking_Program.Models.Booking_DB_Entities();
<select onchange="onChangeBranch()" id="branchStr">
#for (int i = 0; i <= 3;i++ )
{
<option id="#i" value="#i.ToString()">#i.ToString()</option>
}
</select>
}
#Html.TextBoxFor(model => model.Branch, new { id = "branch" })
#Html.ValidationMessageFor(model => model.Branch)
</div>
And javascript is as below.
<script type="text/javascript">
function onChangeBranch() {
var brnch = document.getElementById("branchStr").value;
alert(brnch);
$("#branch").val(brnch).change();
}
</script>
what is wrong with this code? i get alert, but this does not change the value of TextboxFor. How to do it?
I don't know what's the purpose of .change() at the the end of this line
$("#branch").val(brnch).change();
Setting a field value with JQuery is done like this
$("#branch").val(brnch);
or
$("#branch")[0].value = brnch;
I am using MVC in ASP.NET and want a Drag n Drop in my view. I would like to call a function in my controller when the images are dropped to verify them and show an OK to the user. When the user has finished typing in information and dropped the appropriate images he/she clicks "Fortsæt" (continue) and calls submit on the form.
This method should be called when an Image is dropped.
[HttpPost]
[Authorize(Roles = "host")]
public ActionResult UploadImages()
{
bool suc;
foreach (string s in Request.Files)
{
HttpPostedFileBase image = Request.Files[s];
string fileName = Request.Headers["X-File-Name"];
string fileExtension = "";
if (!string.IsNullOrEmpty(fileName))
fileExtension = Path.GetExtension(fileName);
suc = Verify(fileExtension);
}
return Json(suc);
}
This should be called when the user clicks "Continue"
[HttpPost]
[Authorize(Roles = "host")]
public ActionResult Create(FleaMarket model, HttpPostedFileBase[] images)
{
ConditionallySetUser(model, User);
foreach (var fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName.ToString()];
if (file != null && file.ContentLength > 0)
{
var image = HttpPostedFileBaseToByteArray(file);
model.Images.Add(new FleaImage
{
Image = image, FleaMarketId = model.EventId
});
}
}
db.FleaMarkets.Add(model);
db.SaveChanges();
ViewBag.HostID = new SelectList(db.Hosts, "HostId", "Name", model.HostId);
TempData["market"] = model;
return
RedirectToAction("AddStallImage", "FleaMarket");
}
Here are some snips of my View
#model FleaPortal.Models.Database.FleaMarket
<link href="~/Content/basic.css" rel="stylesheet" />
<link href="~/Content/dropzone.css" rel="stylesheet" />
<script src="~/Scripts/dropzone.min.js"></script>
#using (Html.BeginForm("Create", "FleaMarket", method: FormMethod.Post, htmlAttributes: new { #encType = "multipart/form-data",#class="dropzone", #id="dropzoneForm"}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.HostId)
<div class="row">
<div class="form-group col-sm-6">
#Html.LabelFor(model => model.HostId, "Arrangør")
<label class="text-box single-line form-control" id="Name">
#Html.DisplayFor(model => model.Host.UserProfile.UserName)
</label>
</div>
<div class="form-group col-sm-6">
#Html.LabelFor(model => model.Name)
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group col-sm-12">
#Html.LabelFor(model => model.Description)
#Html.EditorFor(model => model.Description, new { #class = "TextAreaInput" })
#Html.ValidationMessageFor(model => model.Description)
</div>
...
...
<div class="form-group col-sm-12">
<label>Stemningsbilleder</label>
<div id="dropzonePreview">
drop your images here
<div class="dz-default dz-message" data-dz-message="">
</div>
</div>
</div>
...
...
<div class="btn-group two-bt-group col-sm-12">
<button name="ButtonType" value="Continue" id="submitAll" type="submit" class="btn btn-success two-bt">#Resources.Views_Global_Continue</button>
<button name="ButtonType" value="Cancel" type="button" class="btn btn-danger two-bt" onclick="location.href='#Url.Action("Manage", "Account")'">#Resources.Views_Global_Cancel</button>
</div>
#section Scripts {
#Scripts.Render("~/bundles/datepicker")
#Scripts.Render("~/bundles/booking")
#Scripts.Render("~/bundles/dropzonescripts")
<script type="text/javascript">
$(document).ready(function() {
$(".form_date").datetimepicker({ format: 'yyyy-mm-dd', startView: 2, minView: 2 });
$(".form_time").datetimepicker({ format: 'hh:ii', startView: 1, maxView: 1 });
});
</script>
<script>
Dropzone.options.dropzoneForm = {
clickable: false,
//url: '/FleaMarket/UploadImages',
autoProcessQueue: false,
uploadMultiple: true,
paramName: "images",// Must match the name of the HttpPostedFileBase argument that the Upload action expects
maxFiles: 100,
autoQueue: false,
previewsContainer: "#dropzonePreview",
parallelUploads:100,
init: function () {
debugger;
this.on("success", function (file, responseText) {
file.previewTemplate.appendChild(document.createTextNode(responseText));
});
}
};
</script>
I have spent way too much time trying to figure this out, and I believe there might be a simple solution - I just don't know. ? Can someone help me figuring this out?
Many thanks in advance.
I ended up calling a method in my controller every time an image was uploaded. I assigned an ID to the imaged and passed it to my view like this:
Dropzone.autoDiscover = false;
$("div#dropzonePreview").dropzone(
{
url: '/FleaMarket/UploadImage',
paramName: "images",
autoProcessQueue: true,
addRemoveLinks: true,
//clickable: "#dropzonePreview",
uploadMultiple: true,
acceptedFiles: "image/*",
maxFiles: 100,
parallelUploads: 10,
dictInvalidFileType: "Dette er ikke et billede",
dictFileTooBig: "Billedet er for stort",
success: function(file, response) {
$('#ImageIds').val($('#ImageIds').val() + "," + response.Ids);
done();
}
});
#Html.HiddenFor(model => model.ImageIds);
<div class="form-group col-sm-12">
<label>Stemningsbilleder</label>
<div id="dropzonePreview" class="dropzone">
</div>
</div>
I have a problem with a variable that take the value undefined.
In the file Create.cshtml i have:
#using (Html.BeginForm("Create", "Enrollment", FormMethod.Post, new
{
id = "YearCourseFormId",
data_courseListAction = #Url.Action("CourseList")
})) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Enrollment</legend>
<div class="editor-label">
#Html.LabelFor(model => model.StudentId, "Student")
</div>
<div class="editor-field">
#Html.DropDownList("StudentId", ViewBag.Student as SelectList, String.Empty, new { #class = "chosen-select", data_placeholder = "Please Select a Student...",style="width:350px;" })
#Html.ValidationMessageFor(model => model.StudentId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Course.YearId, "Year")
</div>
<div class="editor-field">
#Html.DropDownList("YearId", ViewBag.Year as SelectList, String.Empty, new { #class = "chosen-select", data_placeholder = "Please Select a Year...",style="width:250px;" })
#Html.ValidationMessageFor(model => model.Course.YearId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CourseId, "Course")
</div>
<div class="editor-field">
#Html.DropDownList("CourseId", String.Empty)
#Html.ValidationMessageFor(model => model.CourseId)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
In the Jquery File i have:
$(function () {
$('#YearId').change(function () {
var URL = $('#YearCourseFormId').data('courseListAction');
alert(URL);
$.getJSON(URL + '/' + $('#YearId').val(), function (data) {
var selectList = $("#CourseId");
selectList.empty();
var option = $('<option>');
selectList.append(option);
$.each(data, function (index, optionData) {
option = $('<option>').text(optionData.Text).val(optionData.Value);
selectList.append(option);
});
});
});
});
In this part alert(URL);the result is undefined.
In the EnrollmentController.cs i have:
public ActionResult CourseList(string ID)
{
int Year = int.Parse(ID);
var courses = from s in db.Courses
where s.YearId == Year
select s;
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
courses.ToArray(),
"Id",
"CourseName")
, JsonRequestBehavior.AllowGet);
return RedirectToAction("Index");
}
But this method is not called due to error.
What is the problem?
Your form is rendered like this:
<form action="/Enrollment/Create" data-courselistaction="..." id="YearCourseFormId" method="post">
</form>
You can access using any of these:
$('#YearCourseFormId').data('courselistaction');
$('#YearCourseFormId').attr('data-courselistaction');
$('#YearCourseFormId').attr('data-courseListAction');
Given T.J. Crowder's comments about quirks with data(), it would probably be safer to go with one of the attr() solutions.
Edit - The plot thickens..
Chrome inspecter:
Source:
I'm not sure what the implications of that are, but my javascript snippet did work to get the value.
I'm using MVC 4 and Entity Framework to develop an web app. I have a table which contains persons. There is also an Edit button which invokes a modal window and thanks to it, the user can edit a person. I'm using a partial view to do so.
My question is : in my action, I return a View but I just want that when I click on the Save button, the modal window disappear and my table is updated. Any idea?
The actions :
[HttpGet]
public ActionResult EditPerson(long id)
{
var person = db.Persons.Single(p => p.Id_Person == id);
ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name", person.Id_ProductPackageCategory);
return PartialView("_EditPerson", person);
}
[HttpPost]
public ActionResult EditPerson(Person person)
{
ViewBag.Id_ProductPackageCategory = new SelectList(db.ProductPackageCategories, "Id_ProductPackageCategory", "Name", person.Id_ProductPackageCategory);
if (ModelState.IsValid)
{
ModelStateDictionary errorDictionary = Validator.isValid(person);
if (errorDictionary.Count > 0)
{
ModelState.Merge(errorDictionary);
return View(person);
}
db.Persons.Attach(person);
db.ObjectStateManager.ChangeObjectState(person, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
The partial view (actually, the modal window) :
#model BuSIMaterial.Models.Person
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Edit</h3>
</div>
<div>
#using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "table"
}))
{
#Html.ValidationSummary()
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.Id_Person)
<div class="modal-body">
<div class="editor-label">
First name :
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.FirstName, new { maxlength = 50 })
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
Last name :
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.LastName, new { maxlength = 50 })
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
National number :
</div>
<div class="editor-field">
#Html.EditorFor(model => model.NumNat, new { maxlength = 11 })
#Html.ValidationMessageFor(model => model.NumNat)
</div>
<div class="editor-label">
Start date :
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.StartDate, new { #class = "datepicker", #Value = Model.StartDate.ToString("yyyy/MM/dd") })
#Html.ValidationMessageFor(model => model.StartDate)
</div>
<div class="editor-label">
End date :
</div>
<div class="editor-field">
#if (Model.EndDate.HasValue)
{
#Html.TextBoxFor(model => model.EndDate, new { #class = "datepicker", #Value = Model.EndDate.Value.ToString("yyyy/MM/dd") })
#Html.ValidationMessageFor(model => model.EndDate)
}
else
{
#Html.TextBoxFor(model => model.EndDate, new { #class = "datepicker" })
#Html.ValidationMessageFor(model => model.EndDate)
}
</div>
<div class="editor-label">
Distance House - Work (km) :
</div>
<div class="editor-field">
#Html.EditorFor(model => model.HouseToWorkKilometers)
#Html.ValidationMessageFor(model => model.HouseToWorkKilometers)
</div>
<div class="editor-label">
Category :
</div>
<div class="editor-field">
#Html.DropDownList("Id_ProductPackageCategory", "Choose one ...")
#Html.ValidationMessageFor(model => model.Id_ProductPackageCategory) <a href="../ProductPackageCategory/Create">
Add a new category?</a>
</div>
<div class="editor-label">
Upgrade? :
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Upgrade)
#Html.ValidationMessageFor(model => model.Upgrade)
</div>
</div>
<div class="modal-footer">
<button class="btn btn-inverse" type="submit">Save</button>
</div>
}
</div>
And my script which invokes the modal :
$(document).ready(function () {
$('.edit-person').click(function () {
var id = $(this).data("id");
var url = '/Person/EditPerson/'+id;
$.get(url, function(data) {
$('#edit-person-container').html(data);
$('#edit-person').modal('show');
});
});
});
a couple of changes would need to be made but here is what I would do this case
1) change the EditPerson post method from an actionresult to a JsonResult
[HttpPost]
public JsonResult EditPerson(Person person)
{
// code here to save person
bool success = true; // somehow determine if the save was successful
string msg = ""; // error message is needed?
return JsonResult(new {success,msg, person});
}
2) Add a javascript function to close the modal
function closeModal(response){
// the response is the Json Result sent back from the action
if (response.success === true){
// actually got a true response back
}
$('#edit-person').modal('show'); // or similar code
}
3) Then Update your Ajax call to perform code on when its successful
#using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "table",
OnSuccess = "closeModal(response);" // or javascript code to close the modal, you can also
}))
{ ...
a couple of tips
I don't like the MVC ajax helpers. I think they are bloated and I feel there are other frameworks better at it. Thats my opinion. To each their own though. I would prefer to use the jQuery ajax library myself. I think its easier to use but again, its up to you.
The OnSuccess means on "Server Success" not save success. so be careful.
Disclaimer: I wrote this while tired and so it might not be 100% let me know of any issues.
Good luck
In your POST action you could return the following:
return Json(new { error = false, message = "Person edited." });
In the AjaxOptions in Ajax.BeginForm add this:
OnSuccess = "Modal.onAjaxSuccess"
Then somewhere, say in script.js:
function onAjaxSuccess(data, status, xhr) {
if (data.error) {
$.notify({
type: "error",
text: data.message
});
}
else {
$('.modal').modal('hide');
}
}
This will close the window, but I'm still unable to get the darkened screen associated with Bootstrap modals to go away, it also won't update the DIV using AJAX - maybe Darin can shed some light?
If you're still wondering how to do this, this is how:
You have a GET action that returns the list of people:
[HttpGet]
public ActionResult People()
{
return PartialView("_ListOfPeoplePartial");
}
Then have a JS function that fires when you click save (i.e. btn-save-new-person) on the modal that allows you to create new people:
$(function () {
$(document.body).on('click', '#btn-save-new-person', function (e) {
$('#create-new-person-modal').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
var url = "/Home/People";
$.get(url, function (data){
$('#list-of-people').html(data);
});
});
});
in my action, I return a View but I just want that when I click on the Save button, the modal window disappear and my table is updated. Any idea?
Instead of returning a view from this controller action you could return a partial view containing the table. And then in the success callback of the AJAX call simply update the corresponding container.
I've been working through the Contoso University tutorial at http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/, specifically part 6 (http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/updating-related-data-with-the-entity-framework-in-an-asp-net-mvc-application) in which course checkboxes are added to the Instructor Edit view and both the Instructor and Course database tables are updated accordingly.
Unfortunately, the tutorial does not contain how to create a new instructor record and insert to both database tables.
Can anybody offer guidance how to amend the Edit methods to do so?
UPDATE
I'm new to entity framework but am I right in thinking .Add will perform both an insert or an update?
If so, I'm wondering if all I need to change is this bit
var instructorToUpdate = db.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.Courses)
.Where(i => i.InstructorID == id)
.Single();
to create a new id rather than use an existing id?
END OF UPDATE
Http Post Action Method
[HttpPost]
public ActionResult Edit(int id, FormCollection formCollection, string[] selectedCourses)
{
var instructorToUpdate = db.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.Courses)
.Where(i => i.InstructorID == id)
.Single();
if (TryUpdateModel(instructorToUpdate, "", null, new string[] { "Courses" }))
{
try
{
if (String.IsNullOrWhiteSpace(instructorToUpdate.OfficeAssignment.Location))
{
instructorToUpdate.OfficeAssignment = null;
}
UpdateInstructorCourses(selectedCourses, instructorToUpdate);
db.Entry(instructorToUpdate).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DataException)
{
//Log the error (add a variable name after DataException)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
}
PopulateAssignedCourseData(instructorToUpdate);
return View(instructorToUpdate);
}
Other Methods
private void UpdateInstructorCourses(string[] selectedCourses, Instructor instructorToUpdate)
{
if (selectedCourses == null)
{
instructorToUpdate.Courses = new List<Course>();
return;
}
var selectedCoursesHS = new HashSet<string>(selectedCourses);
var instructorCourses = new HashSet<int>
(instructorToUpdate.Courses.Select(c => c.CourseID));
foreach (var course in db.Courses)
{
if (selectedCoursesHS.Contains(course.CourseID.ToString()))
{
if (!instructorCourses.Contains(course.CourseID))
{
instructorToUpdate.Courses.Add(course);
}
}
else
{
if (instructorCourses.Contains(course.CourseID))
{
instructorToUpdate.Courses.Remove(course);
}
}
}
}
...
private void PopulateAssignedCourseData(Instructor instructor)
{
var allCourses = db.Courses;
var instructorCourses = new HashSet<int>(instructor.Courses.Select(c => c.CourseID));
var viewModel = new List<AssignedCourseData>();
foreach (var course in allCourses)
{
viewModel.Add(new AssignedCourseData
{
CourseID = course.CourseID,
Title = course.Title,
Assigned = instructorCourses.Contains(course.CourseID)
});
}
ViewBag.Courses = viewModel;
}
Edit View
#model ContosoUniversity.Models.Instructor
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Instructor</legend>
#Html.HiddenFor(model => model.PersonID)
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.FirstMidName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstMidName)
#Html.ValidationMessageFor(model => model.FirstMidName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.HireDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.HireDate)
#Html.ValidationMessageFor(model => model.HireDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OfficeAssignment.Location)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OfficeAssignment.Location)
#Html.ValidationMessageFor(model => model.OfficeAssignment.Location)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OfficeAssignment.Location)
</div>
<div class="editor-field">
<table style="width: 100%">
<tr>
#{
int cnt = 0;
List<ContosoUniversity.ViewModels.AssignedCourseData> courses = ViewBag.Courses;
foreach (var course in courses) {
if (cnt++ % 3 == 0) {
#: </tr> <tr>
}
#: <td>
<input type="checkbox"
name="selectedCourses"
value="#course.CourseID"
#(Html.Raw(course.Assigned ? "checked=\"checked\"" : "")) />
#course.CourseID #: #course.Title
#:</td>
}
#: </tr>
}
</table>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Question already answered here
I guess I should have searched harder before asking the question!