MVC 4 Optimistic concurrency exception - c#

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.

Related

remove items to a bound list model in ASP MVC.NET

I followed an online tutorial to dynamically add items to a bound list model using ajax, which works perfectly. (http://www.mattlunn.me.uk/blog/2014/08/how-to-dynamically-via-ajax-add-new-items-to-a-bound-list-model-in-asp-mvc-net/comment-page-2/#comment-68909)
My question is, how would I correctly remove items from the list?
Right now what I have done is add a delete link which when clicked removes the item from the view. However, when I submit the form I noticed that the modelState is no longer valid and it has null entries for the item that was removed from the view. So I guess the model is not being updated.
Test.cshtml
#model TesterManager.Models.Test
<div class="form-group">
#Html.LabelFor(model => model.Software, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="form-group">
<div class="col-md-5">
#Html.DropDownListFor(m => m.Software, TesterManager.Models.Helper.GetTestSoftwares(), "Choose a USB Card", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Software, "", new { #class = "text-danger" })
</div>
<div class="col-md-5">
#Html.EditorFor(model => model.Version, new { htmlAttributes = new { #class = "form-control", #title = "Enter a USB FW Version", #placeholder = "Enter a USB FW Version" } })
#Html.ValidationMessageFor(model => model.Version, "", new { #class = "text-danger" })
</div>
<div class="col-md-2">
Delete
</div>
</div>
</div>
</div>
AdminTesterConfigurations.cshtml (snippet):
#model TesterManager.Models.AdminTesterConfigurations
<div class="form-group">
<div class="col-md-6">
....
</div>
</div>
<hr />
<div class="form-group">
<div class="col-md-12">
<h3>Test Software</h3>
<div id="test-list">
#Html.EditorForMany(x => x.Tests, x => x.Index)
</div>
<input type="button" id="add-test" value="Add" />
</div>
</div>
RequestEditViewModel.cshtml:
#model TesterManager.Models.RequestEditViewModel
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.EditorFor(model => model.ShippingLocation)
#Html.EditorFor(model => model.RequesterTesterConfigurations)
#Html.EditorFor(model => model.AdminTesterConfigurations)
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
Edit.cshtml:
#model TesterManager.Models.RequestEditViewModel
#Styles.Render("~/Content/Edit")
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#section Scripts
{
<script>
jQuery(document).ready(function ($) {
$('#add-test').on('click', function () {
jQuery.get('/TesterManager/Request/AddTest').done(function (html) {
$('#test-list').append(html);
});
});
});
</script>
}
#using (Html.BeginForm())
{
<h2>Edit</h2>
#Html.AntiForgeryToken()
#Html.EditorFor(x => x);
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
RequestController.cs
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(RequestEditViewModel request)
{
if (ModelState.IsValid)
{
Request domainRequest = new Request(request);
requests.Add(domainRequest);
return RedirectToAction("Index");
}
return View(request);
}
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult AddTest()
{
var request = new RequestEditViewModel();
request.AdminTesterConfigurations.Tests.Add(new Test());
return View(request);
}
I realized that the problem was that when I would remove the item from the list in the view, I was not removing the hidden input for the collection indexer as well. I updated the code to remove the hidden input and it works fine now.

When view model is loaded, dropdownboxes not populated

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)]

Asp.net MVC 5 ModelValidation is not working

So I have a ViewModel and the properties are all validated by having required attributes on them. When I submit the form it doesn't throw any error messages, i.e. name field is required.
I think I have figured where the problem is. Its in the submit button, how do I get the button to hit the HttpPost method of the ActionList because at the moment its not hitting that, hence the modelstate is not being validated.
View:
<h2>#ViewBag.Title</h2>
<hr>
<div class="well">
#using (Html.BeginForm("BookingDetails", "Booking"))
{
#Html.ValidationSummary(true)
<div class="form-group">
#Html.DisplayNameFor(m => m.FirstName)
#Html.TextBoxFor(m => m.FirstName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FirstName)
</div>
<div class="form-group">
#Html.DisplayNameFor(m => m.Surname)
#Html.TextBoxFor(m => m.Surname, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Surname)
</div>
<div class="form-group">
#Html.DisplayNameFor(m => m.EmailAddress)
#Html.TextBoxFor(m => m.EmailAddress, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.EmailAddress)
</div>
<div class="form-group">
#Html.DisplayNameFor(m => m.MobileNumber)
#Html.TextBoxFor(m => m.MobileNumber, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.MobileNumber)
</div>
<div class="form-group">
#Html.DisplayNameFor(m => m.NumberOfPeople)
#Html.TextBoxFor(m => m.NumberOfPeople, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.NumberOfPeople)
</div>
<div class="form-group">
#Html.DisplayNameFor(m => m.Date)
#Html.TextBoxFor(m => m.Date, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Date)
</div>
<div>
#Html.DisplayNameFor(m => m.Time)
#Html.TextBoxFor(m => m.Time, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Time)
</div>
}
</div>
<div class="form-group">
#Html.ActionLink("Book my table", "BookingDetails", "Booking" new { #class ="btn btn-primary" })
</div>
Controller:
// GET:
public ActionResult BookingDetails()
{
return View();
}
// Post
[HttpPost]
public ActionResult BookingDetails(BookingDetailsViewModel model)
{
if(ModelState.IsValid)
{
return RedirectToAction("BookingConfirmation");
}
return View(model);
}
You have two problems that I can see.
Firstly, your button isn't a submit button. Its a link that sits outside of the form. You must move it into your form and make it a submit button (or write some javascript that submits the form on click):
<div>
#Html.DisplayNameFor(m => m.Time)
#Html.TextBoxFor(m => m.Time, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Time)
</div>
<input type="submit" class="btn btn-primary" /> <!-- move it inside the form -->
#* ^^^^ submit *#
} <!-- end of your form is here -->
Also, Html.ValidationSummary(true) will hide all of your property errors from your Validation Summary. This may not be what you want. If you run into that issue.. remove true from the call.

Fail to submit a list of object to the model binding using ICollection

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

How to add data to both: Category id and Name Category from one Html.LabelFor?

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;

Categories