I have a ViewModel that is used for an edit View. When the data is returned, the ID of the item to be edited does not display on the edit View.
public ActionResult Edit(int id)
{
Parcel parcel = _parcelDao.GetParcel(id);
ParcelEditViewModel viewModel = new ParcelEditViewModel();
viewModel.id = parcel.id;
return View(viewModel);
}
Should I be returning something different to the View?
ViewModel:
public class ParcelEditViewModel
{
public Parcel parcel { get; set; }
public int id { get; set; }
public IEnumerable<SelectListItem> TrackStatus { get; set; }
public ParcelEditViewModel()
{
parcel = new Parcel();
TrackStatus = new List<SelectListItem>
{
new SelectListItem
{
Value = "AwaitingCollection",
Text = "Awaiting Collection"
},
new SelectListItem
{
Value = "OutForDelivery",
Text = "Out For Delivery"
},
new SelectListItem
{
Value = "Delivered",
Text = "Delivered"
}
};
}
public int ParcelStatus { get; set; }
}
View:
//#model ABC.Data.Parcel
#model Abc.ViewModels.ParcelEditViewModel
#{
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>Parcel</legend>
#Html.HiddenFor(model => model.parcel.id)
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Forename)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Forename)
#Html.ValidationMessageFor(model => model.parcel.Forename)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Surname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Surname)
#Html.ValidationMessageFor(model => model.parcel.Surname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.CompanyName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.CompanyName)
#Html.ValidationMessageFor(model => model.parcel.CompanyName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Address1)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Address1)
#Html.ValidationMessageFor(model => model.parcel.Address1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Address2)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Address2)
#Html.ValidationMessageFor(model => model.parcel.Address2)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Address3)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Address3)
#Html.ValidationMessageFor(model => model.parcel.Address3)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.Postcode)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.Postcode)
#Html.ValidationMessageFor(model => model.parcel.Postcode)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ParcelStatus)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.parcel.TrackingStatus, Model.TrackStatus)
#Html.ValidationMessageFor(model => model.ParcelStatus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.TrackingNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.TrackingNumber)
#Html.ValidationMessageFor(model => model.parcel.TrackingNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.parcel.CustomerId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.parcel.CustomerId)
#Html.ValidationMessageFor(model => model.parcel.CustomerId)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
You need to populate all of your view model's properties; not just the ID. The ParcelEditViewModel has no knowledge of what's in your database.
public ActionResult Edit(int id)
{
Parcel parcel = _parcelDao.GetParcel(id);
ParcelEditViewModel viewModel = new ParcelEditViewModel();
viewModel.id = parcel.id;
// Populate other properties! These may not be right.
viewModel.ProductName = parcel.Title;
viewModel.RecipientName; = parcel.RecipientName;
return View(viewModel);
}
There are mapping libraries such as AutoMapper that can help to streamline this.
Related
I have a simple MVC program where earlier I was using one model and the code was working fine. here is the code.
View
#model Microsoft.Azure.ActiveDirectory.GraphClient.User
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Create User</title>
</head>
<body>
<h2>Create User</h2><br />
#using (Html.BeginForm("Create",
"CreateUsers",
new { id = Model != null ? Model.ObjectId : "" },
FormMethod.Post,
new { enctype = "multipart/form-data" })
)
{
<fieldset>
<legend>User</legend>
<div class="editor-label">
#Html.LabelFor(model => model.UserPrincipalName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserPrincipalName)
#Html.ValidationMessageFor(model => model.UserPrincipalName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AccountEnabled)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AccountEnabled)
#Html.ValidationMessageFor(model => model.AccountEnabled)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PasswordProfile.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PasswordProfile.Password)
#Html.ValidationMessageFor(model => model.PasswordProfile.Password)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MailNickname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MailNickname)
#Html.ValidationMessageFor(model => model.MailNickname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DisplayName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.DisplayName)
#Html.ValidationMessageFor(model => model.DisplayName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.GivenName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.GivenName)
#Html.ValidationMessageFor(model => model.GivenName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Surname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Surname)
#Html.ValidationMessageFor(model => model.Surname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.JobTitle)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.JobTitle)
#Html.ValidationMessageFor(model => model.JobTitle)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Department)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Department)
#Html.ValidationMessageFor(model => model.Department)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>
#if (ViewBag.ErrorMessage == "AuthorizationRequired")
{
<p>You have to sign-in. Click #Html.ActionLink("here", "Create", "Users", new { reauth = true }, null) to sign-in.</p>
}
Controller
public async Task<ActionResult> Create(string blobDetails)
{
#region POPULATE USER DETAIL IN CREATEUSER FIELDS
List<string> userDetails = blobDetails.Split(',').ToList();
User user = new User();
user.UserPrincipalName = userDetails[2] + "#xxx.com";
user.GivenName = userDetails[0];
user.Surname = userDetails[1];
user.DisplayName = userDetails[0] + " " + userDetails[1];
return View(Tuple.Create(user);
#endregion
}
[HttpPost]
public async Task<ActionResult> Create([Bind(Include ="UserPrincipalName,AccountEnabled,PasswordProfile,MailNickname,DisplayName,GivenName,Surname,JobTitle,Department")] User user)
{
ActiveDirectoryClient client = null;
client = AuthenticationHelper.GetActiveDirectoryClient();
string name = user.GivenName;
string username = user.UserPrincipalName;
return RedirectToAction("Index");
}
And this works perfectly fine , I get the values of user.GivenName and user.UserPrincipalName from view and I store it into string. Now what I am doing is that I am including one more model into this and trying to get its value from view so I did something like this:
Model
public class CreateUsers
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string PIDetails { get; set; }
public string BlobDetails { get; set; }
public string UserEmail { get; set; }
}
View
#using WebAppGraphAPI.Models
#model Tuple<Microsoft.Azure.ActiveDirectory.GraphClient.User, CreateUsers>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Create User</title>
</head>
<body>
<h2>Create User</h2><br />
#using (Html.BeginForm("Create",
"CreateUsers",
new { id = Model != null ? Model.Item1.ObjectId : ""
},
FormMethod.Post,
new { enctype = "multipart/form-data" })
)
{
#Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.UserPrincipalName)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.UserPrincipalName)
#Html.ValidationMessageFor(tuple => tuple.Item1.UserPrincipalName)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.AccountEnabled)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.AccountEnabled)
#Html.ValidationMessageFor(tuple => tuple.Item1.AccountEnabled)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.PasswordProfile.Password)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.PasswordProfile.Password)
#Html.ValidationMessageFor(tuple => tuple.Item1.PasswordProfile.Password)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.MailNickname)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.MailNickname)
#Html.ValidationMessageFor(tuple => tuple.Item1.MailNickname)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.DisplayName)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.DisplayName)
#Html.ValidationMessageFor(tuple => tuple.Item1.DisplayName)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.GivenName)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.GivenName)
#Html.ValidationMessageFor(tuple => tuple.Item1.GivenName)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.Surname)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.Surname)
#Html.ValidationMessageFor(tuple => tuple.Item1.Surname)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.JobTitle)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.JobTitle)
#Html.ValidationMessageFor(tuple => tuple.Item1.JobTitle)
</div>
<div class="editor-label">
#Html.LabelFor(tuple => tuple.Item1.Department)
</div>
<div class="editor-field">
#Html.EditorFor(tuple => tuple.Item1.Department)
#Html.ValidationMessageFor(tuple => tuple.Item1.Department)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<div class="editor-label">
#*#Html.LabelFor(tuple => tuple.Item2.UserEmail)*#
#Html.EditorFor(tuple => tuple.Item2.UserEmail)
</div>
</body>
</html>
#if (ViewBag.ErrorMessage == "AuthorizationRequired")
{
<p>You have to sign-in. Click #Html.ActionLink("here", "Create", "Users", new { reauth = true }, null) to sign-in.</p>
}
Controller
public async Task<ActionResult> Create(string blobDetails)
{
#region POPULATE USER DETAIL IN CREATEUSER FIELDS
List<string> userDetails = blobDetails.Split(',').ToList();
User user = new User();
user.UserPrincipalName = userDetails[2] + "#gwuadmeaoutlook.onmicrosoft.com";
user.GivenName = userDetails[0];
user.Surname = userDetails[1];
user.DisplayName = userDetails[0] + " " + userDetails[1];
CreateUsers userInfo = new CreateUsers();
userInfo.UserEmail = userDetails[4];
return View(Tuple.Create(user,userInfo));
}
[HttpPost]
public async Task<ActionResult> Create([Bind(Include ="UserPrincipalName,AccountEnabled,PasswordProfile,MailNickname,DisplayName,GivenName,Surname,JobTitle,Department")] User user,[Bind(Include ="UserEmail")] CreateUsers userInfo)
{
ActiveDirectoryClient client = null;
client = AuthenticationHelper.GetActiveDirectoryClient();
string name = user.GivenName;
string username = user.UserPrincipalName;
string Email = userInfo.UserEmail
return RedirectToAction("Index");
}
When I do this I do not get values from View in my controller strings , it shows null. Can you suggest me how can I achieve this.
You could use an object which contains all of the properties you're trying to send to the client. We generally create DTOs for this specific usage. In you're case you'd have:
CreateDto
public class CreateDto
{
public Microsoft.Azure.ActiveDirectory.GraphClient.User User { get; set; }
public CreateUsers UserInfo { get; set; }
}
Then you're controller will be updated as:
public async Task<ActionResult> Create(string blobDetails)
{
#region POPULATE USER DETAIL IN CREATEUSER FIELDS
List<string> userDetails = blobDetails.Split(',').ToList();
User user = new User();
user.UserPrincipalName = userDetails[2] + "#gwuadmeaoutlook.onmicrosoft.com";
user.GivenName = userDetails[0];
user.Surname = userDetails[1];
user.DisplayName = userDetails[0] + " " + userDetails[1];
CreateUsers userInfo = new CreateUsers();
userInfo.UserEmail = userDetails[4];
var dto = new CreateDto() {
User = user,
UserInfo = userInfo
}
return View(dto);
}
[HttpPost]
public async Task<ActionResult> Create([Bind(Include ="UserPrincipalName,AccountEnabled,PasswordProfile,MailNickname,DisplayName,GivenName,Surname,JobTitle,Department")] User user,[Bind(Include ="UserEmail")] CreateUsers userInfo)
{
ActiveDirectoryClient client = null;
client = AuthenticationHelper.GetActiveDirectoryClient();
string name = user.GivenName;
string username = user.UserPrincipalName;
string Email = userInfo.UserEmail
return RedirectToAction("Index");
}
And your view will have:
#using WebAppGraphAPI.Models
#model CreateDto
Later you can reference the information with Model.user and Model.userInfo.
I know this doesn't explain why the Tuple doesn't work. I believe that is best explain by #darin-dimitrov in ado.net mvc3 tuple using in model and single views
Say I want to modify a Movie in a view.
We can do it by the code.
#model MvcMovie.Models.Movie
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Movie</legend>
#Html.HiddenFor(model => model.ID)
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ReleaseDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ReleaseDate)
#Html.ValidationMessageFor(model => model.ReleaseDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Genre)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Genre)
#Html.ValidationMessageFor(model => model.Genre)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Price)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Price)
#Html.ValidationMessageFor(model => model.Price)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
However it is for one movie. But I have many movies say 5. The movie model is a list. How can I loop through it?
Your controller/view model":
public class MovieViewModel
{
public int ID { get; set; }
public string Title { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public ActionResult IndexValid3(IList<MovieViewModel> movieViewModel)
{
//set breakpoint here and update db here
return View(movieViewModel);
}
public ActionResult IndexValid3()
{
IList<MovieViewModel> list = new List<MovieViewModel>();
var movieViewModel = new MovieViewModel { ID = 1, Title = "title1"};
var movieViewModel2 = new MovieViewModel { ID = 1, Title = "title2"};
list.Add(movieViewModel);
list.Add(movieViewModel2);
return View(list);
}
View:
#model IList<Testy20161006.Controllers.MovieViewModel>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexValid3</title>
</head>
<body>
<div>
#using (Html.BeginForm())
{
<table>
#for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>#Html.TextBoxFor(m => Model[i].ID)</td>
<td>#Html.TextBoxFor(m => Model[i].Title)</td>
</tr>
}
</table>
<input type="submit" value="submit" />
}
</div>
</body>
I have a Upload form and I want to pass my information such as an Image and some other field but I don't know how can I upload Image ..
This is My model class
public partial class NewProductCategory
{
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public string ProductPrice { get; set; }
public string ProductImage { get; set; }
public string ProductQuantity { get; set; }
public Nullable<bool> ProductStatus { get; set; }
public Nullable<int> CategoryId { get; set; }
public HttpPostedFileBase user_image_data { get; set; }
public virtual Category Category { get; set; }
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(NewProductCategory productcategory, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
ProductCategory newproductCategory = new ProductCategory();
string path = Path.Combine(Server.MapPath("~/Content/files"), Path.GetFileName(file.FileName));
file.SaveAs(path);
newproductCategory.ProductDescription = productcategory.ProductDescription;
newproductCategory.ProductQuantity = productcategory.ProductQuantity;
newproductCategory.ProductStatus = productcategory.ProductStatus;
newproductCategory.CategoryId = productcategory.CategoryId;
db.ProductCategories.Add(newproductCategory);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "Name", productcategory.CategoryId);
return View(productcategory);
}
And this is My View Code
#model MvcApplication1.Models.NewProductCategory
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>ProductCategory</legend>
#using (Html.BeginForm("Create", "Temp", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<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>
<div class="editor-label">
#Html.LabelFor(model => model.ProductDescription)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductDescription)
#Html.ValidationMessageFor(model => model.ProductDescription)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductPrice)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductPrice)
#Html.ValidationMessageFor(model => model.ProductPrice)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.user_image_data)
</div>
<div class="editor-label">
#Html.Label("Upload your image")
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.user_image_data, new { Type = "File" })
#Html.ValidationMessageFor(model => model.user_image_data)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductQuantity)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductQuantity)
#Html.ValidationMessageFor(model => model.ProductQuantity)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductStatus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductStatus)
#Html.ValidationMessageFor(model => model.ProductStatus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CategoryId, "Category")
</div>
<div class="editor-field">
#Html.DropDownList("CategoryId", String.Empty)
#Html.ValidationMessageFor(model => model.CategoryId)
</div>
<p>
<input type="submit" value="Create" />
</p>
}
</fieldset>
}
please help me in controller i am getting Null value for File upload
Update Ansawer
#model MvcApplication1.Models.NewProductCategory
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm("Create", "Temp", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ #Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>ProductCategory</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>
<div class="editor-label">
#Html.LabelFor(model => model.ProductDescription)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductDescription)
#Html.ValidationMessageFor(model => model.ProductDescription)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductPrice)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductPrice)
#Html.ValidationMessageFor(model => model.ProductPrice)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.user_image_data)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.user_image_data, new { Type = "File" })
#Html.ValidationMessageFor(model => model.user_image_data)
</div>
<div class="editor-label">
#Html.Label("Upload your image")
</div>
<div class="editor-label">
#Html.TextBox("file",null,htmlAttributes: new { Type = "file" })
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductQuantity)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductQuantity)
#Html.ValidationMessageFor(model => model.ProductQuantity)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductStatus)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ProductStatus)
#Html.ValidationMessageFor(model => model.ProductStatus)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CategoryId, "Category")
</div>
<div class="editor-field">
#Html.DropDownList("CategoryId", String.Empty)
#Html.ValidationMessageFor(model => model.CategoryId)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
I have a ViewModel with two models in it which works find when displaying data. My problem is I want to add a foreach() within the Create.cshtml file. Any ideas?
----Create.cshml-----
#model demo.Models.ViewModel
#{ ViewBag.Title = "Create Reference";}<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Submission Form </legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-field">
<!-- iterate through ExternalContentModel and make checkboxes. -->
#foreach (var item in Model.ExternalContentModel)
{
<label class="checkbox">
<input type="checkbox" name="users" value="#item.auth_lname"> #item.auth_lname
</label>
}
</div>
<div class="editor-label">
#Html.LabelFor(model => model.OrganizationName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.OrganizationName)
#Html.ValidationMessageFor(model => model.OrganizationName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Address)
#Html.ValidationMessageFor(model => model.Address)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.City)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
------Controller-----
//
// GET: /Create
public ActionResult Create() <=== can this be the problem????
{
demo.Models.ViewModel vm = new demo.Models.ViewModel();
vm.ExternalContentModel = _repository.ExternalContent();
// Return the content from the External Model to the Create.
return View(vm);
}
//
// POST: /MailingReferences/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Reference reference) <=== can this be the problem????
{
if (ModelState.IsValid)
{
db.References.Add(reference);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(reference);
}
If you have different models then why don't you just create a editor templates for each model?
You can do this by creating a folder called "EditorTemplates" in the same folder your Create.cshtml view lives in. Now add a view for your model into that folder. The view should be named the same as your model class. E.g. a class called FooBarModel would have an editor template called FooBarModel.cshtml.
You would then just use the editor template by doing #Html.EditorFor(x => x.FooBar)
It is a create view page where i have insert supplier information and it is inserting data successfully. i want to get this data automatically when i will enter a name and it exist it will show all of the data in these field, if not exist then i will save to the table.
#model FCBook.Supplier
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Supplier</legend>
<div class="editor-label">
#Html.LabelFor(model => model.SupplierName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SupplierName)
#Html.ValidationMessageFor(model => model.SupplierName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PhoneNo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PhoneNo)
#Html.ValidationMessageFor(model => model.PhoneNo)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Address)
#Html.ValidationMessageFor(model => model.Address)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Area)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Area)
#Html.ValidationMessageFor(model => model.Area)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.District)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.District)
#Html.ValidationMessageFor(model => model.District)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Division)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Division)
#Html.ValidationMessageFor(model => model.Division)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Country)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Country)
#Html.ValidationMessageFor(model => model.Country)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
My controller action to this create view is
public ActionResult Create()
{
return View();
}
//
// POST: /Supplier/Create
[HttpPost]
public ActionResult Create(Supplier collection)
{
try
{
// TODO: Add insert logic here
var db = new PetaPoco.Database("FCBook");
if (collection != null)
{
collection.Insert();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
I think you want to look into using Remote validation. It can be triggered after a user enters a value into one of your fields. I'm using this approach to populate other fields upon such an event occurring.