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.
Related
Is it possible to use validation messages in FluentBootstrap on form element level?
When I use:
#using (var form = Html.Bootstrap().Form().Begin())
{
#form.InputFor(m => m.Name)
#form.Submit()
}
There is no validation, except validation error class on input tag. I want to show validation message for Name property and has-error class on form-group container.
Just add #form.ValidationSummary() where you want the general validation summary to appear. There is an example of this as well as some other examples here: https://github.com/daveaglick/FluentBootstrap/blob/develop/FluentBootstrap.Tests.Web/Views/MvcTests/MvcForms.cshtml
If there is no particular reason to use InpuFor you can do the following.
#form.EditorFor(m => m.Name, addValidationMessage: true)
This will show what error message you put on your Name property's attribute.
Such as
[StringLength(50, ErrorMessage="Cannot be longer than 50 character.")]
public string Name { get; set; }
I personally use the base validation helper
#form.InputFor(m => m.Password, FormInputType.Password)
#Html.ValidationMessageFor(m => m.Password)
I can set the type of the input unlike the case when I use EditorFor
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.
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))
I have a dropdownlist where a user can select a care provider. In the database the value for this is null however in the application, a value is selected. What do I need to do to have the null value appear as a blank? I thought this was the default behavior. I changed to using strongly typed lists in my view model instead of the viewbag and this may have broken at that time.
Here is the view markup:
<div class="editor-label">
#Html.LabelFor(model => model.PsychologistId, "Psychologist")
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.PsychologistId, Model.ListPsychologists)
#Html.ValidationMessageFor(model => model.PsychologistId)
</div>
Here is the property from the view model:
[DisplayName("Psychologist")]
public Nullable<int> PsychologistId { get; set; }
Here is the relevant part of my controller:
model.ListPsychologists = new SelectList(XXX, "Id", "DisplayName");
return this.View(model);
where XXX is just the LINQ expression with filtering and sorting criteria. It's been omitted for clarity and space.
The model passed from the controller to the view has PsychologistId being null. And the SelectedValue property on model.ListPsychologists is null.
if PsychologistId is an int, it will assign 0 value to it since int is not a nullable type.
Show your model and controller if my assumption above is not true.
Does your SelectList contain entry with Id==null? I doubt that. And that means that you will have no select list entry matching your value, so browser will select first one available.
Solution: explicitly add entry with Id = null to your SelectList.
I've had these issues before, and what I did to fix it was send the base collection of what I want to fill the dropdown with in the viewmodel, instead of a SelectList. So:
model.ListPsychologists = XXX;
Then in the view:
#Html.DropDownListFor(x => x.PsychologistId, new SelectList(Model.ListPsychologists, "Id", "DisplayName", Model.PsychologistId))
Please verify the SelectList constructor overload I used in MSDN, I'm typing this from memory. Basically you give it the collection of items to use in the SelectList, then the name of the text and value properties (just like you did in your action method code), and the fourth parameter is the value to set the drop down to.
Edit: Also, there is an overload for the DropDownListFor to add a default item in the menu. Like, "Select One".
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...