Disclaimer: It will be too long as a edit in already existing answer and hence posted in separate answer.
To answer your question on how will you add the UserID
field in your model object below is a detailed description with code segment.
Considering that you have already added Products
entity using ADO.NET Entity Data Model
. Add a separate class file to your Models
folder with any name you like and have the below code. Below code segment decorate your model object.
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace MvcApplication1.Models
{
[MetadataType(typeof(productMetadata))]
public partial class Product
{
}
public class productMetadata
{
[HiddenInput(DisplayValue = false)]
public int ProductId { get; set; }
// to make the field hidden and will not display in browser
[HiddenInput(DisplayValue = false)]
//directing that don't scaffold this column since it will be added manually
[ScaffoldColumn(false)]
public int UserId { get; set; }
}
}
You can directly modify the auto-generated Product
class in EF but if you re-generate the EF model again then the changes will be gone. So, above shown approach is best using MetadataType
attribute.
Controller Action Method(s):
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create([Bind(Include = "ProductName, ProductId")]Product product)
{
SampleContext db = new SampleContext();
if (ModelState.IsValid)
{
product.UserId = (int)Membership.GetUser().ProviderUserKey;
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(product);
}
public ActionResult List()
{
SampleContext db = new SampleContext();
IEnumerable<Product> products = db.Products.ToList();
return View(products);
}
}
}
View (Specifically the Create view):
@model MvcApplication1.Models.Product
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Product</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ProductName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ProductName)
@Html.ValidationMessageFor(model => model.ProductName)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
Notice that the view has editable controls for only productname
as input field since ProductID
is an identity column and UserID
getting value in code and not from user.