Post a model property with DisplayFor on submit - asp.net-mvc

My one view page I passed in a model through the controller, so I can write:
#Html.DisplayFor(m => m.FirstName) which displays the First Name of the model. When I try to submit the form on the page using
#using (Html.BeginForm("CreateUser", "Controller", FormMethod.Post, new { UserViewModel = Model }))
and I take a look at my model in
[HttpPost]
public virtual ActionResult CreateUser(UserViewModel model)
{
//model.FirstName is blank
Is there anyway I can make the model.FirstName not blank? by some how passing the model that I originally passed? I could set a bunch of hidden remarks, though if there is a better way that would be very helpful
EDIT: the DisplayFor is just an example to show the model is accessible. I actually have about 15 fields, and I am going through multiple forms trying to populate the model. Is Hidden the only way? and could I just hide the entire model?

#Html.DisplayFor() creates a simple literal with the value by default (if you're not using a display template), on submit only form elements being submitted to the server.
You can use hidden input.
#Html.HiddenFor(m => m.FirstName)
Which will be something like:
<input type="hidden" value="{the first name}" name="FirstName" id="FirstName" />

Related

how to pass model from view to controller in mvc

I am new to mvc i am trying to pass model into controller from view
This is my view
My Control
but while debugging im getting all null values
i am using view model
where i am doing mistake
Help me
thanks
You cannot use an ActionLink to post a form. Have a look at this post
#model YourViewModel
#using(Html.BeginForm())
{
Model NAme : #Html.TextBoxFor(s=>s.Name)
<input type="submit" value="Post to server" />
}
You seem to use an "ActionLink" to call the "AddUser2" method controller. An ActionLink generates a basic link which redirects to the controller passed in parameter.
You need to post the form (to send values typed by the user to the controller), not redirect.
To post the form, use the following html tag (instead of the ActionLink) :
<input type="submit" value="ok" />
This code generate a button, which will send your form when user will click on it.

Same property in two different tabs (divs). Property is null when tab 2 is posted to action method

When I post back to the server when tab2 is active viewModel.FirstName is null in the action method. How do you tell the modelbinder that it should take #Html.EditorFor(m => m.FirstName) from tab2 when that tab is active? Everything works fine for tab1.
jQuery hide() and show() are used for switching between tabs.
Controller
[HttpPost]
public ActionResult Index(MyViewModel viewModel)
View
<div id="tab1">
#Html.EditorFor(m => m.FirstName)
</div>
<div id="tab2">
#Html.EditorFor(m => m.FirstName)
</div>
It sounds like you have both FirstName input fields inside the same form.
Something like:
<form>
<div id="tab1">
#Html.EditorFor(m => m.FirstName)
</div>
<div id="tab2">
#Html.EditorFor(m => m.FirstName)
</div>
</form>
When you post this, the form is submitted as:
FirstName=valueFromField01&FirstName=valueFromField02
From the behavior you are describing, it seems that once the model binder sets the FirstName field in your MyViewModel, it ignores the second one (but I'm not really sure about that).
Solutions:
Rather than have a form with different tabs inside of it, have a form inside each tab. This will ensure you only have one FirstName inside a form.
Update the model so that you get both fields. You would need to use an array of string: string[] FirstName.
Update:
Instead of updating your ViewModel, it might be easier to simply add another parameter to your action method so you can get both FirstName values and then figure out which one was actually provided:
public ActionResult Index(MyViewModel viewModel, string [] FirstName).
Then you can have logic in your action method to set the FirstName in your viewModel:
if(!string.IsNullOrEmpty(FirstName[0]))
{
viewModel.FirstName = FirstName[0]
}
else if(!string.IsNullOrEmpty(FirstName[1]))
{
viewModel.FirstName = FirstName[1];
}
You could achieve that disabling the duplicated name form elements. By default, disabled form elemnts will not be passed to the request, and your Controller problably will receive the name corectly from the tab2 when it is shown active.
So. here follows one example
$('#tab1')
.hide()
.find('input[name="FirstName]"')
.prop('disabled',true);
$('#tab2').show()
.find('input[name="FirstName]"')
.prop('disabled',false);
Latter I suggest you should wrap this behaviour inside a function.
Hope it helps.

MVC 4 Passing model from one controller to view and from view to other controller without users able to edit all fields

Im kinda new in MVC4 and im not able to figure it out.
"CustomViewMOdel" "CustomViewMOdel"
"ControllerX" ----------------> "VIEW" -----------------> "ControllerY"
My problem is that i want to pass my customviewmodel to view (which is working just fine!). In the View im showing some of model's fields to users (which is working fine also). BUT Now i want user, to change ONE field of the models fields and then PASS the WHOLE model to Controller X (with all fields filled, including the field what user was able to change AND other fields what were just shown)
Can anyone give a very simple code example of how to do this?
You can just create a form that posts to another controller:
ControllerX:
public ActionResult DoSomething()
{
return View(new CustomVM());
}
ViewA
#Model CustomViewModel
#using Html.BeginForm("DoSomethingElse", "ControllerY")
{
#Html.EditorFor(vm => vm.SomeProperty)
<input type="submit" value="OK" />
}
ControllerY
public ActionResult DoSomethingElse(CustomViewModel vm)
{
// do something else
}
You can use #Html.HiddenFor(o => o.Property) on the form.
This will not show a property on it.
But the advanced user may change the property through a development console. So you should check all the changes in the ControllerY
Example:
#Html.HiddenFor(o => o.Id)
#Html.HiddenFor(o => o.Name)
#Html.EditorFor(o => o.Description)
<input type="submit" value="OK" />
This will only let the user change a description but still have "id" and "name" on the FormCollection.

Passing parms to Controller from View with Html.BeginForm

I have two simple questions that I am hoping someone could answer... It's been asked several times on the web, but I cannot find a post that clearly state what I need below...
question 1:
How do you get the values from the View to pass to the Controller where the values already exist on the View? In other words, I need the #loanID value. This value is a textbox on the form and is not part of the model.
<label for="txtLoanID">Loan ID :</label>
#(Html.Kendo().IntegerTextBox()
.Name("txtLoanID")
.Placeholder("Enter LoanID")
)
#using (Html.BeginForm("GeneratePDF", "Home", new { #loanID = loanID }, FormMethod.Post))
question 2:
How can I pass multiple values using the above line to the Controller, specifically, a dropdownlist text value which is also not part of the model.
The textbox should be in the form so it gets posted back by it.
#using (Html.BeginForm("GeneratePDF", "Home", FormMethod.Post)) {
<label for="txtLoanID">Loan ID :</label>
#Html.Kendo().IntegerTextBox().Name("txtLoanID").Placeholder("Enter LoanID")
}
then your controller should be able to get it through model binding
public ActionResult GeneratePDF(int txtLoadID)
{
}

Losing ViewModel Data after POST

I don't see this problem too often but I've got a .cshtml that uses a layout. In the layout I've got:
#using (Html.BeginForm(null, null, FormMethod.Post, new { #class = "someCssClass", #id = "UserForm" }))
{
...rest of the code
}
My main .cshtml using this layout has the model defined at the top as we always do:
#model CarViewModel
#{
Layout = "~/Views/Shared/_CarLayout.cshtml";
}
When It gets back to my action method, I get nulls for all values of the model:
public ActionResult Cars(CarViewModel model)
{
carBL.RemoveCars(model.CarIds, model.DealerId);
...
}
Not sure what I need to do here and why this is happening. Usually I just get it back successfully via autobind. It seems to me when the model is used via RAzor in the markup- that gets posted back fine with the returned ViewModel but if I'm not using those fields, it doesn't...so I assume that's how that works and if I don't use them in mark-up I need to send them back as hidden values then to force the persistence since I am not using x fields from the ViewModel (Which would have automatically persisted those fields if I had used them in the form)?
If the values are not bound to a form field, they will come back null.
in the form use the below for things like ID fields.
#Html.HiddenFor(x => x...)
A quick test, to see if the form is being posted correctly would be to modify the signature of your action:
public ActionResult Cars(FormCollection form)
{
...
}
If form is not populated then you have an issue with the form post. As a side, note you could accomplish this when reviewing the post data of the form with a tool like FireBug, Chrome Dev tools or Fiddler if you prefer.
If the form is posting correctly, then I you should check to make sure the name's of the input fields on the form align with the names of the CarViewModel you are expecting.
Not sure if this has been resolved yet, but this is how I do it (partial code):
#model MyProject.ViewModels.MyViewModel
#using (Html.BeginForm())
{
<table>
<tr>
<td>First Name:</td>
<td>#Html.TextBoxFor(x => x.FirstName, new { maxlength = "50" })
#Html.ValidationMessageFor(x => x.FirstName)
</td>
</tr>
</table>
<button id="btnSave" type="submit">Save</button>
<button id="btnCancel" type="button">Cancel</button>
}
Then my action method to handle the HTTP post request:
[HttpPost]
public ActionResult Create(MyViewModel viewModel)
{
// Check for null on viewModel
// Do what needs to be done
}
Doing it this way should not let you loose your values filled in on the form/view.

Resources