Here are some FAQs on things that were not so obvious. I’ll continue to add to this list over time.
1. Passing HtmlAttributes using @Html.ActionLink
@Html.ActionLink("Create New", "Create", null,
new { style="font-size: .75em; font-weight: normal; padding-left: 15px;" })
2. Html.EditFor with multiline and word wrap support
Use the following data annotation in the model class:
[DataType(DataType.MultilineText)]
public string TextField { get; set; }
This requies the following using statement in the model class:
using System.ComponentModel.DataAnnotations;
Multi-line and word wrap is rendered in the view without any further changes in the controller and view.
3. Pass a variable when using return RedirectToAction
return RedirectToAction("Index", null, new { foo = "some value" });
4. Insert a row and link
This was a frustrating problem that took me some time to resolve. However, the solution is very simple.
See this posting on the ASP.NET MVC forum.
5. Attach existing many-to-many entities using LINQ in the post method
I couldn’t quickly find a simple guide to help me with these basic operations.
It took me a while to work out the solution.
public ActionResult Attach(List<Class> classList, int studentID, string command)
{
if (ModelState.IsValid)
{
int l = command.IndexOf(" ");
int clickedClassID = Int32.Parse(command.Substring(0, l));
var condition = db.Conditions.Find(conditionID);
foreach (var class in classList)
{
if (class.ID == clickedClassID )
if (command.Contains("Attach"))
{
//not sure why I needed to declare the following 2 variables,
//but otherwise it didn't work
var existingClass = db.Classes.SingleOrDefault(x => x.ID == class.ID);
var existingStudent = db.Students.First(x => x.ID == studentID);
existingClass.Students.Add(existingStudent);
db.Classes.Attach(existingClass);
db.Entry(existingClass).State = EntityState.Modified;
db.Entry(existingStudent).State = EntityState.Modified;
db.SaveChanges();
}
else
}
}
return View(db.Classes.ToList());
}
6. Creating local variables in the view from the ViewBag for use in JQuery
<script>
var someStringValue = '@(ViewBag.someStringValue)';
var someNumericValue = @(ViewBag.someNumericValue);
</script>
7. Add a New Row to an Editable Index View
see Stackoverflow at:
http://stackoverflow.com/questions/15249466/mvc-4-partialviewresult-return-partialview-calls-wrong-view-url