During my project I have encountered a problem
I have a table of products and a table of suppliers supplying the products therefore when creating a product i need to choose a specific supplier from the data base the code I have tried so far just chooses an id of supplier which may not exist
<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.SupplierId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SupplierId)
#Html.ValidationMessageFor(model => model.SupplierId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Category)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Category)
#Html.ValidationMessageFor(model => model.Category)
</div>
You can use DropDownListFor helper
<div class="editor-label">
#Html.LabelFor(model => model.Category)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Category)
#Html.ValidationMessageFor(model => model.Category)
</div>
MSDN Article
Related
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)]
I have an Edit view which displays some of my fields as follows:
<table>
<tr>
<td style="width:40%; vertical-align:top">
<div class="editor-label">
#Html.LabelFor(model => model.CREATED_DATE)
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.CREATED_DATE)
#Html.ValidationMessageFor(model => model.CREATED_DATE)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LAST_MODIFIED_DATE)
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.LAST_MODIFIED_DATE)
#Html.ValidationMessageFor(model => model.LAST_MODIFIED_DATE)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.STATUS)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.STATUS, Model.Statuses)
#Html.ValidationMessageFor(model => model.STATUS)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SEVERITY)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.SEVERITY, Model.Severities)
#Html.ValidationMessageFor(model => model.SEVERITY)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PRIORITY)
</div>
<div id="priorityDiv" class="editor-field">
#Html.EditorFor(model => model.PRIORITY)
#Html.ValidationMessageFor(model => model.PRIORITY)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.DESCRIPTION)
</div>
<div id="descriptionDiv" class="editor-field">
#Html.EditorFor(model => model.DESCRIPTION)
#Html.ValidationMessageFor(model => model.DESCRIPTION)
</div>
</td>
</tr>
</table>
In essence I want users to be able to edit any field except for the two at the top, CREATED_DATE and LAST_MODIFIED_DATE. However, when I hit the submit button the two date fields come back as null. My controller code is below.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Alert alert)
{
if (ModelState.IsValid)
{
alert.LAST_MODIFIED_DATE = DateTime.Now;
db.Entry(alert).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(alert);
}
Is there a way to prevent the user from editing a field in a View without the content of filed being returned to the controller as null?
Add them to your view in hidden fields inside the form:
<div class="editor-field">
#Html.DisplayFor(model => model.CREATED_DATE)
#Html.HiddenFor(model => model.CREATED_DATE)
</div>
<div class="editor-field">
#Html.DisplayFor(model => model.LAST_MODIFIED_DATE)
#Html.HiddenFor(model => model.LAST_MODIFIED_DATE)
</div>
This will make them post back to your Edit method without the user being able to edit them. You can also remove the ValidationMessages for this fields as they cannot be edited and therefore won't need to display validation messages.
EDIT:
As #JLRishe pointed out this would give the users the power to edit the values using their browsers debug tools.
Another solution could be to create a view specific model, and only map the values you want adjusted to your database object. More info about that here: Real example of TryUpdateModel, ASP .NET MVC 3
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
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;
Hy Guys!
I don't know how to get this data on my controller. could somebody help me?
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Pedido</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Assunto)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Assunto)
#Html.ValidationMessageFor(model => model.Assunto)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Data)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Data)
#Html.ValidationMessageFor(model => model.Data)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Tks.
You should make an overload of the action method that takes the model as a parameter.
MVC will do the rest.