MVC4: How do I get value from partial view for insert/edit

12,158

Solution 1

SOLVED:

I'd like to thank each of you for your inputs as they did help me in finding a solution. The main part I was missing was this:

@Html.Partial("partialview"), Model.ValueToSend, new ViewDataDictionary(ViewData) {
TemplateInfo = new System.Web.Mvc.TemplateInfo {HtmlFieldPrefix = "ValueToSend"
})

I was missing the templateinfo portion on the parent view. Also, I did change my textbox to TextBoxFor and used:

TextBoxFor(model => model, new { @class = .....)

DO NOT go with model.Value, as I had that in there earlier and was still retrieving a null date value on postback. The solution code does not require a hidden field to be populated, the templateinfo code adds an id to the input field in the partial view and the parent controller automatically grabs the data in the partial's input field to get sent to the database, as if it were one of the other auto generated elements on the parent view.

To make the hidden field idea work, with multiples of the same partial view on the parent view, set the hidden field and date textfield (in this example) to the same id; the hiddenfield you'd put an h in front of it ( e.g. date and hdate). Then you'd need to set a javascript variable to get the id of the active element

var id;
($(".datepickerclass").change(function(){
id = $(this).attr('id');
)}

Additionally, if you're using the datepicker

$(".datepickerclass").datepicker(
.....
beforeShow:
id = $(this).attr('id')

And then add the value to the correct hidden element within the change or blur event of the textbox or within the datepicker:

onSelect: 
var val = $(id).val()
$('#h'+ id).val(val)

Pardon if the jQuery may be off a bit, I shut down my development machine and I'm typing this without fully testing the jQuery code, but I think you'd get the point. Thanks again for all the help. Next up will be tackling a jQuery grid.

Edit: Unfortunately since my rating is not high enough, I cannot upvote the answers provided, as they deserve to be.

Solution 2

If the partial view is within a form element at the top level page, then it will be posted back as if it was part of the original form.

Think of a partial view as being only used at render time. By the time you see the page in your browser, think of it as being one complete page (Not groups of partial views). So any page submit will be done with the whole form in mind.

Solution 3

You have to be aware that anything you do with C# and razor in your views happens before the HTTP response. So once the response is sent to the client, all your @Model.value or @if(something) { @Html.Partial(...) } statements will have already translated into pure HTML.

Something you can do to get values from a partial view to your main view is use jQuery:

Imagine a main view like:

 @Html.HiddenFor(m=>m.ChosenName, new { id="hiddenGlobalName" }

and a partial view like this:

<input type="text" id="partialNameField" />
<input type="button" value="Save and close popup" id="closeButton" />
<script>
    $(function(){
        $('#closeButton').click(function(){
            var partialValue = $('#partialNameField').val();  // get the value
            $('#hiddenGlobalName').val(partialValue);         // "save" to main view
        });
    });
</script>

Because the DOM will be constructed after the HTTP request is over, you have access to all elements of a main view from any included partial view at the time the user sees them.

Hope this can help you!

Solution 4

Use @Html.TextBoxForModel instead of @Html.TextBox(....). This will cause the input to be created with the correct name so that it will bind correctly to your model when you post the page.

You don't need to format the date yourself, you can use the dateFormat option on the jQuery date picker to format the value.

If you use EditorForModel instead of TextBoxForModel, it will create the input with the correct type to use the browsers built in date picker, if available. You can then use Modernizr to test if dates are supported and use the jQuery date picker if it is not. Here is a decent tutorial about it.

Share:
12,158
fafafooey
Author by

fafafooey

Updated on August 21, 2022

Comments

  • fafafooey
    fafafooey over 1 year

    I am new to MVC and I am just trying to get a grip on certain aspects of MVC that I will be using in the project I have coming up. So, I have a view where the user will input data regarding training: name, id, location, and training dates. I have created partial view that will be used for the dates, it incorporates the jQuery date picker and a date mask. This pv will replace date fields where needed. It all works fine, but, I do not know how to get the value placed in the partial view to be passed back into the model, once the user clicks the "Create" or "Edit" button.

    Here is my code (Edit View):

    @Html.Partial("partialview", Model.ValueToPass)
    

    And For the partial view:

    @model Nullable<DateTime>
    @{ 
    string dt = string.Empty;
    if (Model != null) { dt = Model.Value.tostring("MM/dd/yyyy"); }
    <script type="text/javascript">.......</script>
    <p> @Html.TextBox("Test", dt, new {@class = "DateTextArea"}) </p>
    

    As stated, I can get a preexisting date from the model loaded into the textbox, without issue, its just retrieving that value or new value, if the user enters a new date, and putting it into the database. Any help or direction would be of great help. Thank you.

  • fafafooey
    fafafooey over 10 years
    The only reason I added the date formatting is because there is also a masking plugin tied to the field as well; the data being loaded into the field may not be in the correct format either, it has to have the '0' place holders to work correctly (actually, not really the case, I'm just a stickler for conformity). Also, the 'TextBoxForModel', should it be TextBoxFor(Model, ....), because I'm not finding that helper in there.
  • fafafooey
    fafafooey over 10 years
    This is a help, I figured I'd have to use a hidden field, but I wanted to know if there was anything a little more streamlined, as this means more elements, etc. A problem arises when there are multiples of this partial view on a single parent view, if I set the id of the date textbox, there will multiples on the page and jQuery will pitch a fit. I dont think I can pass the Model."ValueToPass" as an id to the element. How could I circumvent this, or would the JQuery not be a problem?
  • cadrell0
    cadrell0 over 10 years
    You are correct on the TextBoxFor(Model. There is EditorForModel and DisplayForModel, so I assumed there was a TextBoxForModel.
  • moritzpflaum
    moritzpflaum over 10 years
    Even though I don't particularly like people posting answers to their own questions, you seem to at least understand what is happening here. If your interested in javascript and dynamic content, one thing I can recommend to look into would be: knockout.js It's a client-side, javascript MVVM framework which easily lets you do things mvc doesn't handle well like create or modify IEnumerable<YourModel>. You have to use a couple of tricks (automatic deserialization from json to POCOs / entities) but once you get the hang of it, it's great.
  • fafafooey
    fafafooey over 10 years
    Thank you for the info. I'm thinking that will be necessary for working with the grid. The only reason I posted an answer is that there are not nearly enough links to this issue, and I think using partial views in this way would be fairly popular. I just wanted to make sure that if someone else happened upon this thread, they'd get the solution they need. Additionally, an extension method should be created to account for null values being passed to the partial view. With dates and simpler datatypes, a basic string model in the pv will work and then manipulate that string as needed.