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)]
Related
I have used an ajax-loader.gif with success in the past, but it was on a filtering for users.
I am now trying to use it on the login form but it doesn't work (loader is not showing)
Here's my code:
#model Models.Login
#using (Ajax.BeginForm("Index", "Login", new AjaxOptions { UpdateTargetId = "ajaxUpdatedPanel", LoadingElementId = "loader" }))
{
<div id="box_login">
<div class="editor-label">
#Html.LabelFor(m => m.Username)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.Username)
#Html.ValidationMessageFor(m => m.Username)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</div>
<br />
<div class="mask roundedCorners" style="float:left;">
<input type="submit" class="btn" value="Logg inn" />
</div>
<div id="loader" style="display:none;float:left;width:100px;margin: 8px 0 0 10px;">
<img src="~/Content/images/loader16.gif" />
</div>
</div>
#Html.ValidationSummary(true)
}
This should do
$(document).ready(function() {
$('form').submit(function() {
if (!someValidations()) {
return false;
} else {
$('form #loader').show();
}
return true;
});
function someValidations() {
return true;
}
});
I am getting a dump ONLY in the server and not in my local system when trying to post the data. There is a page which submits some value to the database. I have also modeled the dropdown in the page as mandatory. However, when clicking on "Create", instead of giving an error like "Missing"; it throws a dump.
Dump trace:
Value cannot be null.
Parameter name: items
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: items
Source Error:
Line 65: </div>
Line 66: <div class="editor-field">
Line 67: #Html.DropDownListFor(x => x.ProjectName, new SelectList(Model.ProjectDetail, "ProjectName", "ProjectName"),"")
Line 68: <span runat="server" style="color:Red;" visible="false"> *</span>
Line 69: #Html.ValidationMessageFor(model => model.ProjectName)
Source File: d:\hosting\11178048\html\fbpm\fbpm\Views\User\Create.cshtml Line: 67
Stack Trace:
[ArgumentNullException: Value cannot be null. Parameter name: items] System.Web.Mvc.MultiSelectList..ctor(IEnumerable items, String dataValueField, String dataTextField, IEnumerable selectedValues)
+289714 System.Web.Mvc.SelectList..ctor(IEnumerable items, String dataValueField, String dataTextField) +19 ASP._Page_Views_User_Create_cshtml.Execute() in d:\hosting\11178048\html\fbpm\fbpm\Views\User\Create.cshtml:67 System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197 System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +81 System.Web.WebPages.StartPage.RunPage() +17
The Controller code:
public ActionResult Create()
{
var model = new UserDetail
{
ProjectDetail = db1.ProjectDetails.ToList()
};
return View(model);
}
//
// POST: /User/Create
[HttpPost]
public ActionResult Create(UserDetail userdetail)
{
if (ModelState.IsValid)
{
db.UserDetails.Add(userdetail);
db.SaveChanges();
return RedirectToAction("SearchCust");
}
return View(userdetail);
}
The view code:
#model fbpm.Models.UserDetail
#{
ViewBag.Title = "Create Customer";
}
<h2>Create Customer</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>Customer Detail</legend>
<div id ="left" style="float:left; width:400px;">
<div class="editor-label">
#Html.LabelFor(model => model.UserID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserID)
<span runat="server" style="color:Red;" visible="false"> *</span>
#Html.ValidationMessageFor(model => model.UserID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Password)
<span runat="server" style="color:Red;" visible="false"> *</span>
#Html.ValidationMessageFor(model => model.Password)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PANNo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PANNo)
#Html.ValidationMessageFor(model => model.PANNo)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EmailID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EmailID)
#Html.ValidationMessageFor(model => model.EmailID)
</div>
<br />
<p>
<input type="submit" value="Create Customer" />
</p>
</div>
<div id = "left3" style="float:left; width:400px">
<div class="editor-label">
#Html.LabelFor(model => model.ProjectName)
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.ProjectName, new SelectList(Model.ProjectDetail, "ProjectName", "ProjectName"),"")
<span runat="server" style="color:Red;" visible="false"> *</span>
#Html.ValidationMessageFor(model => model.ProjectName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.BookedDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.BookedDate)
<span runat="server" style="color:Red;" visible="false"> *</span>
#Html.ValidationMessageFor(model => model.BookedDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.BookedAmount)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.BookedAmount)
<span runat="server" style="color:Red;" visible="false"> *</span>
#Html.ValidationMessageFor(model => model.BookedAmount)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Contact1)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Contact1)
#Html.ValidationMessageFor(model => model.Contact1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Contact2)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Contact2)
#Html.ValidationMessageFor(model => model.Contact2)
</div>
</div>
<div id="left1" style="float:left; width:400px;">
<div class="editor-field">
#Html.HiddenFor(model => model.Role, new { #readonly = "readonly", #Value = "400" })
#Html.ValidationMessageFor(model => model.Role)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.FullAddress)
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.FullAddress)
#Html.ValidationMessageFor(model => model.FullAddress)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.State)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.State)
#Html.ValidationMessageFor(model => model.State)
</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>
</div>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "SearchCust")
</div>
I have searched a lot in the net and found that adding a viewbag for the project name in the submit action before returning the view owuld help; but, it didnt. Please can someone help?
Regards
I'm assuming you only see this exception when your insert fails; you then try to reuse the UserDetail model in the view for the same page.
The error you are seeing is due to the nature of working with HTTP - anything that is not directly bound to an input is not retained. So, when you attempt to rebuild the view, the list you are trying to bind the drop-down helper to is null, since UserDetail.ProjectDetail has not been repopulated. You can fix this like so:
[HttpPost]
public ActionResult Create(UserDetail userdetail)
{
if (ModelState.IsValid)
{
db.UserDetails.Add(userdetail);
db.SaveChanges();
return RedirectToAction("SearchCust");
}
userdetail.ProjectDetail = db1.ProjectDetails.ToList();
return View(userdetail);
}
I noticed that create button is a submit button
So it must call action with HttpPost attribute
[HttpPost]
public ActionResult Create(UserDetail userdetail)
In this action, it returns View(userdetail);
But this userdetail object is created by model binder from the submit data from browser.
So it won't have values in ProjectDetail property.
You can step it through
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;