Modify property in a list with razor - asp.net-mvc

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>

Related

View returns null value when using two models in MVC

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

Uploading Image in Asp.net mvc Controller

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>
}

ViewModel does not populate input fields

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.

Values in model are null or empty

I have this action method
[HttpPost]
public ActionResult CreateEsf(EsfLotDetailsModel model)
{
...
}
I have two properties in this model. One is a database POCO object and the other is a list. In the GET equivalent of this method, these values were all populated correctly, but on post these get set to null (the POCO) and empty (the list).
Why might this be?
My view is here
#using UI.Helpers
#model UI.Areas.Admin.Models.EsfLotDetailsModel
#{
ViewBag.Title = "Create Forward Lot";
}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/AdminDesignTheme/js/wl_Date.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Content/AdminDesignTheme/js/wl_Time.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.mousewheel.min.js")" type="text/javascript"></script>
#{
<script type="text/javascript">
$(document).ready(function () {
var options = {
dateFormat: "dd/mm/yy"
};
$('#Starts').wl_Date(options);
$('#Ends').wl_Date(options);
$('#startTime').wl_Time();
$('#endTime').wl_Time();
});
</script>
}
<p>#Html.ActionLink("Back to Item List", "Index","Inventory")</p>
#Html.ValidationSummary(true, "Please correct the errors and try again.")
#using (Html.BeginForm(new {model = #Model})) {
#Html.HiddenFor(model => model.Auction.InventoryReference)
#Html.HiddenFor(model => model.Auction.Title)
#Html.HiddenFor(model => model.Auction.Description)
<fieldset>
<legend></legend>
<label>ESF Lot Information</label>
<section>
#Html.LabelFor(model => model.Auction.Title)
<div> #Html.DisplayFor(model => model.Auction.Title)
#Html.ValidationMessageFor(model => model.Auction.Title) </div>
</section>
<section>
#Html.LabelFor(model => model.Auction.Description)
<div> #Html.DisplayFor(model => model.Auction.Description)
#Html.ValidationMessageFor(model => model.Auction.Description) </div>
</section>
#if (HttpContextHelper.IsUserAdmin())
{<section>
<label for="IsFeatured">Is Featured <i>(displayed in homepage)</i></label>
<div> #Html.CheckBoxFor(model => model.Auction.IsFeatured)
#Html.ValidationMessageFor(model => model.Auction.IsFeatured) </div>
</section>
}
else
{
<section>
<label for="IsFeatured">Is Featured <i>(displayed in homepage)</i></label>
<div> #Html.CheckBoxFor(model => model.Auction.IsFeatured, new { disabled = "disabled" }) (Contact Admin to make this a featured lot)
#Html.ValidationMessageFor(model => model.Auction.IsFeatured) </div>
</section>
}
#if (HttpContextHelper.IsUserAdmin())
{<section>
#Html.Label("VAT Applicable")
<div> #Html.CheckBoxFor(model => model.Auction.VatApplicable)
#Html.ValidationMessageFor(model => model.Auction.VatApplicable) </div>
</section>
}
else
{
<section>
#Html.Label("VAT Applicable")
<div> #Html.CheckBoxFor(model => model.Auction.VatApplicable, new { disabled = "disabled" }) (Contact Admin if it is not VATable)
#Html.ValidationMessageFor(model => model.Auction.VatApplicable) </div>
</section>
}
</fieldset>
<fieldset>
<legend></legend>
<label>Date and Time</label>
<section>
<label>Starts <em>(dd/mm/yy hh:mm)</em></label>
<div> <input type="text" class="date" id="Starts" />
<input type="text" class="time" data-connect="Starts" id="startTime" />
#Html.ValidationMessageFor(model => model.Auction.Starts) </div>
</section>
<section>
<label>Ends <em>(dd/mm/yy hh:mm)</em></label>
<div> <input type="text" class="date" id="Ends" />
<input type="text" class="time" data-connect="Ends" id="endTime" />
#Html.ValidationMessageFor(model => model.Auction.Ends) </div>
</section>
<section>
#Html.LabelFor(model => model.Auction.IsExtensible)
<div> #Html.CheckBoxFor(model => model.Auction.IsExtensible)
#Html.ValidationMessageFor(model => model.Auction.IsExtensible) </div>
</section>
</fieldset>
<fieldset>
<legend></legend>
<label>Bid Options</label>
<section>
#Html.LabelFor(model => model.Auction.StartingBid)
<div> #Html.TextBoxFor(model => model.Auction.StartingBid)
#Html.ValidationMessageFor(model => model.Auction.StartingBid) </div>
</section>
<section>
#Html.LabelFor(model => model.Auction.Reserve)
<div> #Html.TextBoxFor(model => model.Auction.Reserve)
#Html.ValidationMessageFor(model => model.Auction.Reserve) </div>
</section>
<section>
<label>Reserve Visible <em>(Displays as Reserve met or not met)</em></label>
<div> #Html.CheckBoxFor(model => model.Auction.ReserveVisible)
#Html.ValidationMessageFor(model => model.Auction.ReserveVisible) </div>
</section>
<section>
#Html.LabelFor(model => model.Auction.IsBidIncrementPercentual)
<div> #Html.CheckBoxFor(model => model.Auction.IsBidIncrementPercentual)
#Html.ValidationMessageFor(model => model.Auction.IsBidIncrementPercentual) </div>
</section>
<section>
#Html.LabelFor(model => model.Auction.BidIncrement)
<div> #Html.TextBoxFor(model => model.Auction.BidIncrement, new { #Value = 1m })
#Html.ValidationMessageFor(model => model.Auction.BidIncrement) </div>
</section>
<section>
#Html.LabelFor(model => model.AuctionEvents)
<div> #Html.DropDownList("Auction", Model.AuctionEvents, "Select auction", new { required = "required" })
#Html.ValidationMessageFor(model => model.AuctionEvents) </div>
</section>
<section>
<div><button>Create</button></div>
</section>
</fieldset>
}
<div>
#Html.ActionLink("Back to Item List", "Index","Inventory")
</div>
Add FormMethod = FormMethod.Post to your Html.BeginForm()
#using (Html.BeginForm("Action", "Controller",FormMethod.Post))
{
}
where is your submit button?
#using (Html.BeginForm("Action", "Controller",FormMethod.Post))
{
...
<input type="submit" value="submit" />
}
when you fill in the form, press the submit button, then enter in the [HttpPost] Method and value of Model will be filled.
None of these options worked. I put all the values in the POCO object separately in the model instead and removed the POCO object. No idea why it doesn't work.

Ajax.BeginForm redirects action page(MVC 4)

I use 'Ajax.BeginForm' in my application,but for some reason my form is redirecting to {controller}/{action} with right json data instead of start {OnComplete = "Add_OnComplete"}:
View:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
#using (Ajax.BeginForm("Create", new AjaxOptions { OnComplete = "Add_OnComplete"}))
{
<fieldset>
<legend>Add</legend>
<div class="editor-label">
#Html.LabelFor(model => model.FullName)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.FullName)
#Html.ValidationMessageFor(model => model.FullName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PhoneNumber)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.PhoneNumber)
#Html.ValidationMessageFor(model => model.PhoneNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Status)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Status)
#Html.ValidationMessageFor(model => model.Status)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<script type="text/javascript">
function Add_OnComplete(context) {
var JsonAdd = context.get_response().get_object();
if (JsonAdd.Success) {
//TODO
}
}
</script>
Controller:
public PartialViewResult Create()
{
return PartialView();
}
[HttpPost]
public JsonResult Create(Subscribe model)
{
if (ModelState.IsValid)
{
_entity.CreateSubscribe(model, SubscribeStatus.Customer.GetHashCode());
var message = new Message(MailSubject, MailBody, model.Email);
message.Send();
}
return Json(new
{
Success = true,
Message = "The person has been added!"
});
}
What I do wrong ? And what am I missing?
Thanks.
Remove that get_response().get_object() stuff.
Use just context.Success

Resources