MVC Model not passed to controller - asp.net-mvc

Am almost embarassed that I can't get this to work. I have a model like this:
public class Test
{
public string Test1 {get; set; }
public string Test2 {get; set; }
}
I have a razor view which correctly displays both Test1 and Test2. Test1 is displayed just like this:
#Html.LabelFor(model => mode.Test1)
#Html.Test1
Test2 is displayed like this:
#Html.LabelFor(model => model.Test2)
#Html.EditorFor(model => model.Test2)
i.e. I just want to display Test1, but want the user to be able to edit Test2.
These are within a form:
#using(Hmtl.BeginForm("Action1", "Controller1", FormMethod.Post)
In Controller1.Action1 it receives the model:
public ActionResult Action1(Test m)
{
}
but in here m.Test1 is null, m.Test2 is correctly populated. m.test1 is correctly displayed in the view.
Am confused.com
Thanks in advance,
Ray

The model binder only sees the form values which are posted from the HTML form, which are only from form elements. This doesn't generate such an element:
#Html.Test1
That may display the value to which the view is bound (does it really? I've never seen it done like that, maybe that should be #Model.Test1?) but there needs to be an HTML form element of some kind to post a value back to the server. (input, select, hidden, etc.)
For fun, take a look at the HTML generated in the browser. They're just standard form elements with values, there's nothing storing the whole model anywhere. The model binder just tries to intelligently re-construct a model based on the name/value pairs sent from the HTML form.
Try adding a hidden field to the form as well:
#Html.LabelFor(model => model.Test1)
#Model.Test1
#Html.HiddenFor(model => model.Test1)
This should create an input type="hidden" in the form with that value, which would be included when posting the values to the controller action.

Related

How to hide primary key input field using editorfor

Hi I'm using Editorfor() to make a little form that submits view model to the controller. Editorfor() nicely prints input fields of the model but it also prints primary key field. So I want to hide primary key field.
#Html.EditorFor(m=>m.viewmodel)
this is markup that I have.
#Html.HiddenFor(m => m.viewmodel.Id);
#Html.EditorFor(m=>m.viewmodel)
have tried this but does not work. and I wanted to make an approach directly to the model but I'm using EF Designer, so I'm not sure where to begin. Please give me an advice.
Try this:
[HiddenInput(DisplayValue = false)]
public int ProductID { get; set;
Use a custom editor template. For example:
MyViewModel.cshtml (stored in ~/Views/Shared/EditorTemplates folder, structured like a partial view):
#model MyViewModel
#Html.HiddenFor(m => m.Id)
#Html.EditorFor(m => m.Property1)
#Html.TextboxFor(m => m.Property2)
#Html.TextAreaFor(m => m.Property3)
// Whatever else you want in the template
Then you can just call EditorFor on your model in your view that needs to use it and MVC will know to use your custom template:
#Html.EditorFor(m => m.MyViewModel)
To use a custom display template that isn't based on the name of the type, you can also use the [UIHint] attribute as described here: http://www.growingwiththeweb.com/2012/12/aspnet-mvc-display-and-editor-templates.html
Don't create any field for your key attribute. Without a field to check, the validation has nothing to complain about. Later you can supply a value for the primary key in the controller.

DataAnnotation validation attributes do not work when field is rendered in partial view

I have a simple model that has a string property that has validation put on it via dataannotations.
When this is rendered in the main form validation works as expected. If I move the field to a partial view the validation no longer works.
My main and partial views contain this:
#Html.EditorFor(m => m.MyNumber)
#Html.ValidationMessageFor(m => m.MyNumber)
My model looks like this:
[Remote("IsValidMyNumber", "Home",
ErrorMessage = "This does not appear to be a valid Number.")]
public string MyNumber { get; set; }
Simply moving the code in the view from the view to the partial view will cause the validation to not be called.
Why is this?
Because I am rendering the partial in a #section of the page it is not being included in my Form tags. So therefore is not being validated.

Attaching a hidden text field to a form MVC

This very well may end up being a very silly question in a way but basically I have this "form" in a model that gets attached to my View as the form but I haven't been able to actually pass any data do it from the View. It only has two properties: an Id property and a String property. I've been trying to fill the String property with text from a hidden text box on the page with no luck.
Form code:
public class AllocateListForm
{
public int Id { get; set; }
public virtual string HiddenText { get; set; }
}
Relevant View code:
<% using (Html.BeginForm("SaveExit", "User", new { }, FormMethod.Post, new { id = "selectExitPoints" })) { %>
<fieldset>
<input type="hidden" id="HiddenText" />
</fieldset>
<% } %>
There is JQuery behind the scenes that fills HiddenText with text and I can assure you that it is filling. There is also JQuery behind the scenes that performs an Ajax submission and I can promise you that code works as it is used elsewhere in the application without a problem. When I perform the action that submits the form to the server and I go to my controller code that this points to, I have a breakpoint set so I can go into the console and check if the HiddenText field on the form has any data it is null. Can anybody point me in the right direction?
If you assign the input's name to be "HiddenText" the model binder should pick it up. I'm assuming that your controller action accepts an AllocateListForm as a parameter.
<input type="hidden" name="HiddenText" id="HiddenText" />
You can also use Html Helpers like so:
#Html.HiddenFor(model => model.HiddenText, new { id = "HiddenText" })
EDIT: Add an AllocateListForm as a property of your main model and then change the helper to be #Html.HiddenFor(model => model.MyAllocateListForm.HiddenText)
This should do the trick, if you want to do it the Razor-way.
#Html.HiddenFor(model => model.HiddenText);

Pass an entire model on form submission

I understand that I can use #Html.HiddenFor(m => m.parameter) and when the form is submitted, that parameter will be passed to the controller. My model has many properties.
Is there a shorter way of passing the entire model at once to the controller or must I do it one by one each time?
The model will be passed to the controller in its entirety, but the values of properties that are not bound by input or hidden fields will be lost.
You have to either bind the properties in the form on the client-side, or re-fetch the entity on the server-side.
You seem to be asking for something like #Html.HiddenFor(m => m.Model), and that is not possible. Sorry
One thing to keep in mind, if you have tons of hidden fields, you may be sending more data to the view than you really need. Consider employing view models
For anyone else who looks at this you can do a #Html.EditorForModel() in a hidden div. You'd also have to use #Html.EditorFor(model => model.ObjectProperty) for each object property of the model.
<div hidden="hidden">
#Html.EditorForModel()
#Html.EditorFor(model => model.ObjectProperty)
#Html.EditorFor(model => model.ListOfObjectsProperty)
</div>
The entire model will be posted if you are using a FORM element. Your elements using the Model obviously need to be inside the form element
You can also POST the form yourself say by using JQuery
See this other stack issue for that : jQuery AJAX submit form
Have a close look at the anwser by "Alfrekjv"
This is already built in. Consider this model:
public class MyModel
{
public string PropertyA { get; set; }
public string parameter { get; set; }
}
and now consider this action:
[HttpPost]
public ActionResult PostSomeData(MyModel model)
{
}
MVC will leverage the FormCollection and fill in the MyModel class where it can. If you don't have the PropertyA in the form then it will be null. But since you have an input for the parameter property it will be filled in.
You can check only the properties you want:
if (this.ModelState.IsValidField("Name"))
{
// .....
}
instead of:
if (this.ModelState.IsValid)
{
// .....
}
#using (Ajax.BeginForm("my_function", "my_controller", new AjaxOptions { InsertionMode = InsertionMode.Replace }, mymodel))

How do I set up a check box with ASP MVC in my view?

I have the following class:
public class City {
public string Name { get; set; }
public bool CityValid { get; set; }
}
I know how to set up the name but how can I set up the CityValid field so it acts like a checkbox. I'd like to do this without using HTML helpers.
If you really don't want to use helpers, you would use a normal HTML input tag:
<input type="checkbox" id="CityValid" name="CityValid" value="#Model.CityValid" />
<input type="hidden" id="CityValue_Hidden" name="CityValid" value="false" />
The name attribute has to match your property name so that the model binder will pick it up correctly when you post back to the server.
When you use the helpers, something similar to the above markup will be generated. The hidden field is there so that a value is always sent with the form post data, regardless of whether you check the box or not (if you leave the box unchecked, no value gets sent by default, not even a 'false').
However, unless you're doing something really weird, I'd recommend you stick to using the helpers. Either:
#Html.CheckboxFor(m => m.CityValid)
or
#Html.EditorFor(m => m.CityValid)
In your view you could use the EditorFor helper:
#model City
...
#Html.EditorFor(x => x.CityValid)
The default editor template for a boolean field generates a checkbox.
You could first create it with a HTML-helper, look at the markup that gets created when running the page, and then recreate that markup...

Resources