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.
Related
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
In this instance I have two pages, in the post method of the first I return the view/viewmodel of the second like so :
[HTTPPost]
public Task<ActionResult> Page1(Page1Model model)
{
var Page2Model = GrabDataMethod(model);
return View("Page2", Page2Model); //Point 1
}
[HTTPPost]
public Task<ActionResult> Page2(Page2Model model //Point 2)
{
var updatedModel= RunFiltersMethod(model)
return View(updatedModel);
}
Now, in this case Page2 renders properly from (Point 1) with all values passed in above from the GrabDataMethod. However, when I POST for Page2 the Page2Model I receive at (Point 2) has none of the original entries, e.g. everything not modified directly by Page2 itself is null or default (in fact it seems the model from the post method is a new model entirely). I've made a horrible workaround for the time being, but I need a proper fix, is there any reason that this would be happening?
Page2 View Code
#model Mvc2013.Models.Page2Model
#using (Html.BeginForm("Page2", "Controller"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
<div class="row">
<div class="col-md-12">
#Html.Kendo().Chart(<!-- code removed, this is working -->)
</div>
</div>
<div class="row">
<div class="col-md-3">
<div class="col-md-8">
#Html.LabelFor(model => model.Prop1, new { #class = "control-label" })
</div>
<div class="col-md-4">
#Html.EditorFor(model => model.Prop1, new { #class = "control-label" })
#Html.ValidationMessageFor(model => model.Prop1)
</div>
</div>
<div class="col-md-3">
<div class="col-md-8">
#Html.LabelFor(model => model.Prop2, new { #class = "control-label" })
</div>
<div class="col-md-4">
#Html.EditorFor(model => model.Prop2, new { #class = "control-label"})
#Html.ValidationMessageFor(model => model.Prop2)
</div>
</div>
</div>
<!-- This carries on similarly for lots more attributes -->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Inside the Beginform you should add #Html.HiddenFor(model => model.Something) where the Something are the properties which you want back on the postback.
If you don't then the property values will be default values.
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
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].
}