Within my project I am trying to change the users ability from only being able to "Edit" an address field to being able to "Create" and "Edit" if it already exist within the same view. I receive the following server error Click Here.
I then ran it through the debugger and received the following result Click Here Too!. I can see that my User ID is being passed as null in the controller which creates the server error. But after following Mr. Pratt advice I can see the User Id is being passed into the View I am unsure why this is happening or where I've made the mistake.
Controller
// GET: /UserProfile/Edit/5
public ActionResult Edit(int id)
{
var userProfile = db.UserProfiles.FirstOrDefault(up => up.UserId == id);
var query = from o in db.UserProfiles
where o.Address != null
select o;
ViewBag.Query = query;
// if the user is not an admin
if (!User.IsInRole("admin"))
{
// look up current user id
var currentUserId = (int)System.Web.Security.Membership.GetUser().ProviderUserKey;
// check to make sure that the user profile is attached to the currently logged in user
if (userProfile.UserId == currentUserId)
{
return View(userProfile);
}
else
{
throw new Exception("you cannot access a user profile that is not your own");
}
}
// the user is an admin, so let them view the profile
return View(userProfile);
}
View
#model YardLad.Models.Domain.UserProfile
#{
ViewBag.Title = "Edit Profile";
}
<h2>Edit Profile</h2>
#if (User.IsInRole("contractor") || User.IsInRole("contractor2"))
{
<style>
#content a {
color: cornflowerblue;
}
#content a:hover {
color: cornflowerblue;
}
</style>
}
<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)
#Html.HiddenFor(m => m.UserId)
#Html.HiddenFor(m => m.AcceptSMS)
#Html.HiddenFor(m => m.IsActive)
#Html.HiddenFor(m => m.LastLoginDate)
#Html.HiddenFor(m => m.AddressId)
<div class="editor-label">
Name
</div>
<div class="editor-field">
#Html.EditorFor(m => m.FirstName)
#Html.ValidationMessageFor(m => m.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(m => m.LastName)
#Html.ValidationMessageFor(m => m.LastName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Phone)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.Phone)
#Html.ValidationMessageFor(m => m.Phone)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Mobile)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.Mobile)
#Html.ValidationMessageFor(m => m.Mobile)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DateOfBirth)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.DateOfBirth)
#Html.ValidationMessageFor(model => model.DateOfBirth)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Gender)
</div>
<div class="editor-field">
#Html.RadioButton("Gender", "male") male
#Html.RadioButton("Gender", "female") female
#Html.ValidationMessageFor(m => m.Gender)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AddressId, "Address")
</div>
var address = ViewContext.ViewData.ModelState["Address"];
if (address != null && address.Errors.Count() > 0)
{
#Html.ActionLink("Add a billing address", "Create", "Address",
new { returnUrl = "UserProfile/Edit", userId = Model.UserId }, null)
}
else
{
<div class="editor-field">
#Html.DisplayFor(m => m.Address.Line1)<br />
#*#if (Model.Address.Line2 != null && address.Any())
{
#Html.DisplayFor(m => m.Address.Line2)<br />
}*#
#Html.DisplayFor(m => m.Address.City), #Html.DisplayFor(m => m.Address.State.Abbreviation) #Html.DisplayFor(m => m.Address.PostalCode)
</div>
if (ViewBag.Query != null || ViewBag.Query != "" )
{
#Html.ActionLink("Add an address", "Create", "Address", new { id = Model.AddressId, returnUrl = "UserProfile/Edit", userId = Model.UserId }, null)
}
else
{
#Html.ActionLink("Edit address", "Create", "Address", new { id = Model.AddressId, returnUrl = "UserProfile/Edit", userId = Model.UserId }, null)
}
}
#*<div class="editor-field">
<span>#Html.CheckBoxFor(m => m.AcceptSMS)</span>
<span class="editor-label">
#Html.LabelFor(m => m.AcceptSMS, "Accept SMS Service")
</span>
<p style="width: 50%; min-width: 300px;">
this free service allows you to send and receive text updates for easier access to making payments, scheduling reoccurring services, rating services, etc.<br />
<span style="font-size: .9em; color: forestgreen;">standard SMS charges still apply (based on your mobile carrier and plan)</span>
</p>
</div>*#
<p>
<input type="submit" value="Save" />
</p>
}
<div>
#Html.ActionLink("Back to My Account", "MyAccount", "Account")
</div>
userProfile is null. You need to do proper null-checking:
var userProfile = db.UserProfiles.FirstOrDefault(up => up.UserId == id);
if (userProfile == null)
{
return new HttpNotFoundResult();
}
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I have a form, which gets some values from model. Then, in POST the data user entered are handled and user is redirected to another page. However everytime I post the form, I get null-reference exeption. Where do I make a mistake?
None of the other questions asking about this didn´t solve my problem, that´s why I am asking again with my specific code.
The exeptions are at foreach loops - Model.Cart, Model.ShippingOptionsm etc.
#model CheckoutViewModel
#{
ViewBag.Title = "Checkout";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Checkout</h2>
<table class="table">
<thead>
<tr>
<td>#</td>
<td>Name</td>
<td>Quantity</td>
<td>Price</td>
<td>Total price</td>
</tr>
</thead>
#foreach (CartItem i in Model.Cart)
{
<tr>
<td>#Html.Action("ProductPosition", "Cart", new { item = i })</td>
<td>#i.Name</td>
<td>#i.Quantity</td>
<td>#i.Price €</td>
<td>#i.Total €</td>
</tr>
}
</table>
<h3>Total: #Html.Action("TotalPrice", "Cart") €</h3>
#using (Html.BeginForm("Checkout", "Cart"))
{
#Html.AntiForgeryToken()
<h2>Address</h2>
<div class="form-group">
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Name)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Address)
#Html.TextBoxFor(m => m.Address, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Address)
</div>
<div class="form-group">
#Html.LabelFor(m => m.City)
#Html.TextBoxFor(m => m.City, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.City)
</div>
<div class="form-group">
#Html.LabelFor(m => m.PostNumber)
#Html.TextBoxFor(m => m.PostNumber, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.PostNumber)
</div>
<div class="form-group">
#Html.LabelFor(m => m.State)
#Html.TextBoxFor(m => m.State, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.State)
</div>
<h2>Shipping</h2>
foreach (var i in Model.ShippingOptions)
{
<div class="radio">
#Html.RadioButtonFor(m => m.ShippingOption, i.Id) #i.Name - #i.Price €
</div>
}
#Html.ValidationMessageFor(m => m.ShippingOption);
<h2>Payment</h2>
foreach (var i in Model.PaymentOptions)
{
<div class="radio">
#Html.RadioButtonFor(m => m.PaymentOption, i.Id) #i.Name
</div>
}
#Html.ValidationMessageFor(m => m.PaymentOption);
<button type="submit" class="btn btn-primary">Continue</button>
}
#section scripts
{
#Scripts.Render("~/bundles/jqueryval")
}
Controller:
public ActionResult Checkout()
{
if (Session["cart"] == null)
return RedirectToAction("Index");
var checkout = new CheckoutViewModel()
{
Cart = (List<CartItem>)Session["cart"],
PaymentOptions = _context.PaymentOptions.ToList(),
ShippingOptions = _context.ShippingOptions.ToList()
};
return View(checkout);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Checkout(CheckoutViewModel m)
{
if (!ModelState.IsValid)
return View();
//TODO: handle data
return RedirectToAction("OrderSuccess");
}
Add model declaration at the top of the page
#model CheckoutViewModel
I'm using C# ASP.NET MVC with Entity Framework, trying to create a web application that doesn't really need to be on more than one 'page', using partial views and dialogs for everything.
The index page displays a table, and there are jquery buttons that link to dialogs, which contain partial views for doing stuff with.
I'm currently dealing with the partial view responsible for adding and editing entities in the table. It adds them fine, and the partial works great for that, but when I try to load an object into the viewmodel, things go awry. The entity itself is entirely complete, no worries there, but not all the information is loaded in the partial view, and some of it is in the wrong format. Specifically,
All those dropdownboxes should be filled. They are populated, just not with the right value. Also, there is code in the viewmodel that should stop the date from appearing as it does;
[Required]
[Display(Name = "Date Requested")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public System.DateTime DateRequested { get; set; }
The controller action that presents the partial view is as such;
public ActionResult _advisoryRequestForm(string id = "")
{
ViewBag.datepickeruid = Guid.NewGuid();
setViewBagNewAR();
if (id.Equals(""))
return PartialView();
BCRTAdvisoryRequest request = new AdvisoryRequestsLogic().getAdvisoryRequestByID(Convert.ToInt32(id));
return PartialView(request);
}
The ajax call;
$(".editRequest").button().on("click", function () {
$.ajax({
url: 'Home/_advisoryRequestForm',
type: 'POST',
data: "&id="+this.id,
success: function (response) {
if (response) {
$('#ardialog-form').html(response);
requestForm = $('#ardialog-form').find('#advisoryRequestForm');
$.validator.unobtrusive.parse(requestForm);
editRequestDialog.dialog("open");
}
},
error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
});
});
The partial view returned;
#model EH.BCRT.AdvisoryRequests.Model.BCRTAdvisoryRequest
<link href="#Url.Content("/Content/Site.css")" rel="stylesheet" />
<link href="#Url.Content("/Content/themes/base/jquery.ui.dialog.css")" rel="stylesheet" />
<link href="#Url.Content("/Content/themes/base/jquery.ui.datepicker.css")" rel="stylesheet" />
<form id="advisoryRequestForm">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>BCRTAdvisoryRequest</legend>
<div class="container">
<div class="h-double">
<div class="editor-label">
#Html.LabelFor(m => m.RequestTypeID)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.RequestTypeID)<br />
#Html.DropDownListFor(m => m.RequestTypeID, (IEnumerable<SelectListItem>)ViewBag.RequestTypeID, "", null)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.DateRequested)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.DateRequested)<br />
#Html.TextBoxFor(model => model.DateRequested, new { #class = "datepickerfield", id = ViewBag.datepickeruid })
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SiteName)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.SiteName)<br />
#Html.EditorFor(model => model.SiteName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ServiceCategoryID)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.ServiceCategoryID)<br />
#Html.DropDownListFor(m => m.ServiceCategoryID, (IEnumerable<SelectListItem>)ViewBag.ServiceCategoryID, "", null)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.Description)<br />
#Html.TextAreaFor(model => model.Description, new { style = "width:95%;min-height:80px;" })
</div>
</div>
<div class="h-double">
<div class="editor-label">
#Html.LabelFor(model => model.RequestedBy)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.RequestedBy)<br />
#Html.EditorFor(model => model.RequestedBy)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.JobTitle)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.JobTitle)<br />
#Html.EditorFor(model => model.JobTitle)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LocalOfficeOrTeam)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.LocalOfficeOrTeam)<br />
#Html.EditorFor(model => model.LocalOfficeOrTeam)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SiteVisit)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.SiteVisit)<br />
#Html.EditorFor(model => model.SiteVisit)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StatusID)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.StatusID)<br />
#Html.DropDownListFor(m => m.StatusID, (IEnumerable<SelectListItem>)ViewBag.StatusID, "", null)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ConsultantRetained)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.ConsultantRetained)<br />
#Html.EditorFor(model => model.ConsultantRetained)
</div>
</div>
<div class="h-single">
<div class="editor-label">
#Html.LabelFor(model => model.Comments)
</div>
<div class="editor-field">
#Html.ValidationMessageFor(model => model.Comments)<br />
#Html.TextAreaFor(model => model.Comments, new { style = "width:95%;min-height:80px;" })
</div>
</div>
</div>
</fieldset>
}
</form>
<script type="text/javascript">
$(document).ready(function () {
$('.datepickerfield').each(function () {
$(this).datepicker({ dateFormat: 'dd-mm-yy' });
});
});
</script>
Any ideas on what might be wrong with the dropdowns and the date field?
setViewBagNewAR()
private void setViewBagNewAR()
{
var ARLogic = new AdvisoryRequestsLogic();
ViewBag.StatusID = ARLogic.getRequestStatuses();
ViewBag.RequestTypeID = ARLogic.getRequestTypes();
ViewBag.ServiceCategoryID = ARLogic.getServiceCategories();
}
SelectLists placed in the ViewBag should be named differently than all of your model properties.
For example, you can rewrite the controller for status id to:
ViewBag.StatID = ARLogic.getRequestStatuses();
Then, change the DropDownlistFor in your View to
#Html.DropDownListFor(m => m.StatusID, (SelectList)ViewBag.StatID, "", null)
As for the date format, there is an ApplyFormatInEditMode property which will apply format to dates in an EditorFor.
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
Having faced this issue (I wanted to allow an edit by using a bootstrap modal window, i'm using MVC4 and entity framework), when I want to save my changes, I have this error message since I'm using the modal window :
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.
Here are my 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 View("Index");
}
return View(person);
}
My partial view :
#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()
<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>
}
Any idea on what's going on?
Try this first, just above #Html.ValidationSummary() in the partial view where you have the modal head, body and footer, place:
#Html.HiddenFor(model => model.PersonId) // or.Id whatever's in your model
This creates a hidden field in your view and sets model ID i.e. PK.
i have added extra three input fields to my view to enable the system admin to submit four objects at the same time instead of one object at a time; the view looks as the following:-
#model Elearning.Models.Answer
#{
ViewBag.Title = "Create";
}
<div id = "partialWrapper">
#using (Ajax.BeginForm("Create", "Answer", new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "incrementanswer",
OnSuccess = "removePartial",
LoadingElementId = "progress2"
}))
{
<div id = "returnedquestion">
#Html.ValidationSummary(true)
<fieldset>
<legend>Answer here</legend>
<ol>
<li> <div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.TextBox("answer[0].Description")
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.IsRight)
</div>
<div class="editor-field">
#Html.DropDownList("IsRight", String.Empty)
#Html.ValidationMessageFor(model => model.IsRight)
</div>
</li>
<li> <div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.TextBox("answer[1].Description")
#Html.ValidationMessageFor(model => model.Description)
</div> <div class="editor-label">
#Html.LabelFor(model => model.IsRight)
</div>
<div class="editor-field">
#Html.DropDownList("IsRight", String.Empty)
#Html.ValidationMessageFor(model => model.IsRight)
</div> </li>
<li> <div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.TextBox("answer[2].Description")
#Html.ValidationMessageFor(model => model.Description)
</div> <div class="editor-label">
#Html.LabelFor(model => model.IsRight)
</div>
<div class="editor-field">
#Html.DropDownList("IsRight", String.Empty)
#Html.ValidationMessageFor(model => model.IsRight)
</div> </li>
<li> <div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.TextBox("answer[3].Description")
#Html.ValidationMessageFor(model => model.Description)
</div> <div class="editor-label">
#Html.LabelFor(model => model.IsRight)
</div>
<div class="editor-field">
#Html.DropDownList("IsRight", String.Empty)
#Html.ValidationMessageFor(model => model.IsRight)
</div> </li>
<ol>
</fieldset>
<input type= "hidden" name = "questionid" value = #ViewBag.questionid>
<input type= "hidden" name = "assessmentid" value = #ViewBag.assessmentid>
<input type="submit" value="Add answer" />
</div>
}
</div>
and the following Post Ation Method:-
[HttpPost]
public ActionResult Create(int questionid, ICollection<Answer> answer)
{
if (ModelState.IsValid)
{
foreach (var a in answer){
repository.AddAnswer(a);
repository.Save();
}
return PartialView("_details2",answer);
}
return View("_details2",answer);}
and last thing the _details2 partial view which contains the newly added objects:-
#model IEnumerable<Elearning.Models.Answer>
#{
ViewBag.Title = "Details";
}
#foreach (var m in Model)
{
<tr id = #m.AnswersID>
<td>
#Html.DisplayFor(modelItem => m.Description)
</td>
<td>
#*#Html.DisplayFor(modelItem => Model.Answer_Description.description)*#
#ViewBag.Answerdesription
</td>
<td>
#Ajax.ActionLink("Delete", "Delete", "Answer",
new { id = m.AnswersID },
new AjaxOptions
{
Confirm = "Are You sure You want to delete this Answer ?",
HttpMethod = "Post",
UpdateTargetId = #m.AnswersID.ToString(),
OnSuccess = "removePartial2"
})
</td>
</tr>
}
but the above is not working nethier the objects will be added nor the partial view will be returned , so how i can solve this issue???
BR
You bind your view to a single Elearning.Models.Answer object, how are you expecting to get a collection of Answers as a parameter in your Action? The default model binder will try to bind your view fields to the parameter in the Action but it won't be able to as it's a collection.
What you could try to do is to bind your View to a List<Elearning.Models.Answer> and feed it 4 empty Answer objects, then you can create a strongly typed Partial view that expects one Elearning.Models.Answer, add the Partial in a foreach and, when posting the form, expect that the default model binder does it work and fill your action method with a brand new List of Answer objects.
As an alternative, you can create a View Model object that contains the fields in your View, including those 4 description fields. You add them as Html.TextboxFor to bind each of them to a different property in the View Model. Then you can collect them in your action, provided you change it to public ActionResult Create(int questionid, ViewModelAnswer answer)
Does it make sense?
Your model should contain a list and code like this:
#for (int i=0; i < Model.FavouriteMovies.Count; i++) {
#Html.LabelFor(model => model.YourList[i].Field)
#Html.EditorFor(model => model.YourList[i].Field)
#Html.ValidationMessageFor(model => model.YourList[i].Field)
}
which will print something like:
<label for="YourList_0__Field">Field Name</label>
The Field Name field is required.
And receive the model back in your controller:
public ActionResult MyAction(MyModel model)
{
// First element?
model.YourList[0].
}
In the view Create i want to add a new product. I need from the drop down list to select the category name. The problem is, that i have in the table Products add only the category id. And how me add and name too of category?
Structure my DB:
Table Brand: idbrand, name.
Table Make: idbrand, namebrand, idmake, name, price, urlmake.
I do the following:
// GET: /ShopManager/Create
public ActionResult Create()
{
ViewBag.BrandID = new SelectList(db.Brand, "BrandID", "Name");
return View();
}
//
// POST: /ShopManager/Create
[HttpPost]
public ActionResult Create(Make make)
{
if (ModelState.IsValid)
{
db.Make.AddObject(make);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.BrandID = new SelectList(db.Brand, "BrandID", "Name", make.BrandID);
return View(make);
}
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Марка телефона</legend>
<div class="editor-label">
#Html.LabelFor(model => model.BrandID, "Бренд")
</div>
<div class="editor-field">
#Html.DropDownList("BrandID", String.Empty)
#Html.ValidationMessageFor(model => model.BrandID)
</div>
<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.Price, "Цена")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Price)
#Html.ValidationMessageFor(model => model.Price)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.UrlMake, "Изображение")
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UrlMake)
#Html.ValidationMessageFor(model => model.UrlMake)
</div>
<p>
<input type="submit" value="Создать" />
</p>
</fieldset>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
How me add in Table Make BrandID and Name of Brand(name of Category)?
Since you have a Brand table it's not necessary to store brand's name in the Make also, you could get that with a simple join. Anyway if you really want to do that in the Create you can set it as the following code
make.NameBrand = db.Brand.Where(b => b.idbrand == make.idbrand).SingleOrDefault().namebrand;