How do I post varied length list to controller? - asp.net-mvc

MVC4. I have a dynamic list on a view, a new textbox is added with button click (which adds a partialView) so user can enter a list of stuff. That is contained in a form element with a submit button.
In the controller I have tried three different types:
[HttpPost]
public ActionResult Index(IEnumerable<AccessoryVM> form)
{
-- form is NULL
[HttpPost]
public ActionResult Index(AccessoryVM form)
{
-- form has only the first item in the list
[HttpPost]
public ActionResult Index(FormCollection form)
{
-- seems to receive the list, but having trouble getting the values
All the examples I have seen are using a for list to add an index to each item, but they aren't using a dynamic list (it has a fixed length).
What should the Controller receiving type be?
EDIT to add more detail:
Button click appends partial view:
$("#add-item").on("click", function () {
$.ajax({
url: '/Accessory/AddItem',
cache: false,
success: function (html) {
$("#form-body").append(html);
}
})
return false;
})
Partial View:
#model EmployeeHardwareRequest.Models.ViewModels.AccessoryVM
<div class="form-group col-md-3">
#Html.LabelFor(model => model.ItemDescription, htmlAttributes: new { #class = "control-label" })
<div>
#Html.DropDownListFor(model => model.AccessoryId, Model.AccessoryDdl, new { #class = "form-control" })
</div>
</div>
<div class="form-group col-md-9">
#Html.LabelFor(model => model.ProductLink, htmlAttributes: new { #class = "control-label" })
<div>
#Html.EditorFor(model => model.ProductLink, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductLink, "", new { #class = "text-danger" })
</div>
</div>
Main View - partial is appended to the #form-body:
#using (Html.BeginForm("Index", "Accessory", FormMethod.Post, new { #id="accessory-form", #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div id="form-body">
<div class="form-group col-md-3">
#Html.LabelFor(model => model.ItemDescription, htmlAttributes: new { #class = "control-label" })
<div>
#Html.DropDownListFor(model => model.SelectedAccessory, Model.AccessoryDdl, new { #class = "form-control" })
</div>
</div>
<div class="form-group col-md-9">
#Html.LabelFor(model => model.ProductLink, htmlAttributes: new { #class = "control-label" })
<div>
#Html.EditorFor(model => model.ProductLink, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductLink, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<button id="add-item" class="btn btn-primary">Add Another Item</button>
</div>
<div class="col-md-6">
<input type="submit" value="Select Software" class="btn btn-default pull-right" />
</div>
</div>
}

Most likely, you have a binding issue. Assuming all you're posting is a collection of AccessoryVM, then the parameter should be List<AccessoryVM> form. However, in order for the modelbinder properly bind the posted values, your input names must be in a specific format, namely either form[N].Foo or just [N].Foo.
You haven't given any detail about what's going on in your view, but since these are dynamically added, you must be using JavaScript to add additional inputs to the page. If you're doing it via AJAX (returning a partial view), you'll need to pass the index to your endpoint so that it can be utilized to generate the right input names. If you're using something like Knockout, Angular, etc., you should ensure that whatever template is being used to generate the inputs takes an index into account.

Related

Inputs inside Partialview takes value from main model

I render a PartialView inside my main View
View:
#model FullProductViewModel
...
<div class="send-container">
#Html.Partial("_CommentForm", new CommentViewModel { ProductId = Model.Id, Title = "" , Context="" })
</div>
...
I have a filed with name "Title" in Both my classes "FullProductViewModel" and "CommentViewModel".
_CommentForm PartialView:
#model CommentViewModel
<p class="page-title">#Resources.SendComment</p>
#using (Html.BeginForm("Comment", "Home", FormMethod.Post, new { #class = "form-comment form-submit" }))
{
#Html.AntiForgeryToken()
<div class="input-group">
#Html.LabelFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="input-group">
#Html.LabelFor(model => model.Context)
#Html.ValidationMessageFor(model => model.Context, "", new { #class = "text-danger" })
#Html.TextAreaFor(model => model.Context, htmlAttributes: new { #class = "form-control", rows = "8" })
</div>
<div class="input-group">
#Html.LabelFor(model => model.CaptchaCode)
#Html.ValidationMessageFor(model => model.CaptchaCode, "", new { #class = "text-danger" })
#Html.EditorFor(model => model.CaptchaCode, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="captcha-wrapper">
<img alt="Captcha" id="imgcaptcha" src="#Url.Action("Captcha", "Captcha")" />
</div>
<button class="btn btn-submit" type="submit">#Resources.SendMessage</button>
}
The problem is "Title" inside PartialView take its value form "FullProductViewModel" model but not "CommentViewModel ". i can easily change the field name "Title" inside one of models to solve problem... but why this happened and how i can fix it without change field name?
Your Title property is conflicting with the #{ ViewBag.Title = ".. line of code in your view (the ViewBag code is used by the _Layout.cshtml file to set the global <title> attribute for the page).
All the HtmlHelper methods that generate form controls set the value by checking (in order)
ModelState
The ViewDataDictionary (ViewData or ViewBag)
The value of the models property
In your case, nothing has been added to ModelState. But because a value for Title has been added to the ViewDataDictionary, its that value which is used for the value of your textbox. The method never gets to read the actual value you have set in your model.
The only realistic option (unless you want to modify the code in the _Layout and all views that use it) is to change the name of the property.

ASP.Net MVC: Partial view not rendering

i am bit new in asp.net mvc. i am facing problem for very basic things that my Partial view not rendering. here is the details
i have a main page and one partial view
main page action look like
public ActionResult Index()
{
return View();
}
main index view look like
#model Testing.Models.Employee
#{
ViewBag.Title = "Home Page";
}
<div class="row">
</div>
<div class="row">
<div id="formsIndex">
#{
Html.Partial("_TestForm");
}
</div>
</div>
#section scripts {
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
}
here i am showing a partial view like this way Html.Partial("_TestForm"); but no UI comes for partial view.
partial view code look like
#model Testing.Models.Employee
#using (Ajax.BeginForm("Index", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "formsIndex" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.City, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</div>
</div>
}
when i pass model to partial view this way Html.Partial("_TestForm", Model); then also no UI comes.
please tell me where i made the mistake ?
use in method return PartialView() and try this
#Html.Partial("_TestForm");
Using Html.Partial inside a #{ ... } block will just call the method and throw the result away.
You should call it outside of a #{ ... } block, prefixed with #, and remember to pass in the model:
<div id="formsIndex">
#Html.Partial("_TestForm", Model);
</div>
Render like this
#Html.Action("_Partialview", "controllerName")
also create action methode of partial view
public ActionResult _Partialview
{
Employee _objModel= new Employee ()
return PartialView(_objModel);
}

CSS Class for DropDownListFor

Using scaffolded items in an MVC5 application, I see things like text fields given the CSS class "form-control". The fields all have consistent rounded corners, same font color/size etc.
Now I've added a dropdown list using "#Html.DropdownListFor" and it's square, with a different font colour.
I know I can specify which CSS class to use in the Razor e.g.
#Html.DropDownListFor(model => model.OrderItemTypeId, (SelectList)ViewBag.OrderItemTypes, new { htmlAttributes = new { #class = "###########" } })
But I don't know what to replace ########### with. If I specify "form-control" just gives me the square box I described above. "form-control select" doesn't seem to do much either.
Here's a bigger snippet showing a well-styled text field directly above it
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderItemTypeId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.OrderItemTypeId, (SelectList)ViewBag.OrderItemTypes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.OrderItemType, "", new { #class = "text-danger" })
</div>
</div>
Is there a value I can use that will give my dropdown the same appearance as all the other text fields I already have?
Thanks
The third parameter already is the htmlAttributes field, so your syntax is wrong. This is what you're after:
#Html.DropDownListFor(model => model.OrderItemTypeId,
(SelectList)ViewBag.OrderItemTypes,
new { #class = "form-control etc" })
See Microsoft Docs.
You need to make sure it sits within proper hierarchy of outer tags with their corresponding classes.
See the code below that I took from this article - How to use Bootstrap 3 validation states with ASP.NET MVC Forms
<div class="row">
<div class="col-sm-4 col-sm-offset-4">
<div class="panel panel-default">
<div class="panel-body">
#using (Html.BeginForm("UserProfile", "Profile", FormMethod.Post, new { role = "form", id="userForm" })) {
#* State selection dropdown *#
<div class="form-group">
#Html.LabelFor(m => m.State)
#Html.DropDownListFor(m => m.State, // Store selected value in Model.State
// This argument needs some explanation - here we take a Distionary<string, string>
// and turn it into an instance of SelectList, see blog post for more details
new SelectList(Model.States, "Key", "Value"),
// Text for the first 'default' option
"- Please select your state -",
// A class name to put on the "<select>"
new { #class = "form-control" }
)
#Html.ValidationMessageFor(m => m.State)
</div>
<button type="submit" class="btn btn-primary">Update</button>
}
</div>
</div>
</div>
</div>

searching database and displaying on .cshtml page

I have this code in my controller:
public ActionResult Search(String searchstring)
{
var number = from n in db.UCountInfoes
select n;
if (!String.IsNullOrEmpty(searchstring))
{
number = number.Where(i => i.IDNumber.Equals(searchstring));
}
return View(number);
}
and on my .cshtml page i have this which i use to search:
<div class="form-group">
#Html.LabelFor(model => model.ID_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ID_Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ID_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" name="SearchButton" value="Search" class="btn btn-inverse" />
</div>
</div>
After clicking the search button i want to return the records found on another .cshtml page.
return RedirectToAction("Action Name", "Your Controller Name", number);
Instead of return View you can use the above method.
Here Action Name is the View Name you want to show the results into.

Asp.Net MVC: Why is my view passing NULL models back to my controller?

I cannot figure out why my view only passes back a NULL for a model to my controller.
This is for an Edit Post method. I checked other controllers with Edit Post methods that are structured the same way as this one and they work fine. It seems to be just this view and controller.
Here is my view:
#model Non_P21_Quote_System_v1._0.Models.gl_code
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
#if (TempData["Message"] != null)
{
<div style="color:green">
#TempData["Message"]
</div><br />
}
#if (ViewBag.error != null)
{
<div style="color:red">
<h3>#ViewBag.error</h3>
</div><br />
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>gl_code</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.GL_code, "GL Code", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.GL_code, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.GL_code, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GL_description, "Gl Description", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.GL_description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.GL_description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.expense_type_ID, "Expense", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("expense_type_ID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.expense_type_ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.eag, "Employee Account Group", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("eag", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.eag, "", new { #class = "text-danger" })
</div>
</div>
<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>
}
<div>
#Html.ActionLink("Back to List", "gl_Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Here is my controller method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "ID,GL_code,GL_description,expense_type_ID,eag")] gl_code gl_code)
{
if (ModelState.IsValid)
{
db.Entry(gl_code).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("gl_Index");
}
ViewBag.eag = new SelectList(db.employee_account_group, "ID", "eag_name");
ViewBag.expense_type_ID = new SelectList(db.expense_type, "ID", "type", gl_code.expense_type_ID);
return View(gl_code);
}
When I debug it, I see the model being passed in is of value NULL. I am seeing this on the controller side at the the parameters part of the Edit method.
Its null because your model contains a property named gl_code and you have also named the parameter for your model gl_code in the POST method.
Change the name of one or the other and the model will bind correctly.
What is happening internally is that the form submits a name/value pair for each successful form control, in your case gl_code=someValue. The DefaultModelBinder first initializes a new instance of your model. It then reads the form values and finds a match for the property in your model and sets it to someValue. But it also finds a match in the method parameters and tries set the value of the parameter to someValue, which fails (because you cannot do gl_code gl_code = "someValue";) and the model becomes null.
It appears you have a property on your view model called gl_code. In your controller, you also refer to the view model as gl_code.
Try changing this.
public async Task<ActionResult> Edit(gl_code gl_code)
To
public async Task<ActionResult> Edit(gl_code model)

Resources