tags:

views:

46

answers:

1

Hi all,

Head scratching :( I am trying to bind one value to label and back to model from label , but not working I can see the value in View but after post action controller method Model is not having that value.

Please suggest ! Can't Label values posted to the server like classic asp.net ?

public class MyModel
    {
        public MyModel()
        { 

        }

        public string FirstName {set; get;}

        public string Desciptopn { set; get; }

        public string EventDate2 { set; get; }

        public bool Failed { set; get; }



    }




<%
              EventDate2.Text = Model.EventDate2;
        %>
            <asp:Label ID="EventDate2" runat="server" Text="Label"></asp:Label>
+1  A: 

Don't use server side controls with MVC. These values are not persisted (no viewstate) back to the server. If you need the value passed back as part of the model, you should put it in an HTML input, perhaps hidden, in addition to including the text on the page.

<% using(Html.BeginForm()) { %>
  <%= Html.Hidden( "EventDate2" ) %>
  <%= Html.Encode( Model.EventDate2 ) %>
<% } %>

Anything you want sent back needs to be either part of a URL (for a GET request) or a form input. These will get translated to your action method parameters/model.

tvanfosson
Thanks tvanfosson, Do you mean I should use <%= Html.Hidden( "EventDate2" ) %>or <%= Html.Encode( Model.EventDate2 ) %> Note : I need that EventDate2 back to server Sorry asking stupid question , i am newbie
prakash
Thanks i think i got you , Hidden field for getting back to server and Encode for showing to user .... Is there any drawback for using Hidden Field ?
prakash
@prakash -- because it's on the form, it can technically be modified by the end user even it is hidden, i.e., the user can craft a post that changes this value. If it's important that it not be modified, which is presumably why you'd use a label instead of textbox, then I'd cache the data on the server (maybe in session) and reuse it. Only you can know whether there is a risk in using the hidden field.
tvanfosson
@prakash -- one thing you probably do want to do is use the AntiForgeryValidation attribute on your methods that accept posts in conjunction with generating the anti-forgery token with the HtmlHelper on the form itself. This will help protect you from certain types of attacks.
tvanfosson