Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Everybody,

I have a Model Class Payment in which have (In Payment Constructor) i am passing the values of its properties values. It is working fine in the HttpGet Action. but when i am posting this form then Payment Properties does not having the properties.


SQL
Payment paymentobj1 = new Payment();  //Here Paymentobj1 having all values in this properties
UpdateModel(paymentobj1);  //After executing UpdateModel the paymentobj1 values will be loss.


Please suggest me what is wrong with that.

SQL
public class Payment
{
public Payment()
{
//Get the Value from the Static Method and set into the property.
ProductItems = StaticClass.StaticMethod();
}
public list<items> ProductItems  {get;set;}
}


//Here is the place where i am not able to get the value of Property : In Controller
[HttpPost]
public ActionResult Index (Payment paymentobj)
{
//Here i am getting payment.ProductItems Value is null  ???

Payment paymentobj1 = new Payment();  //Here Paymentobj1 having all values in this properties
UpdateModel(paymentobj1);  //After executing UpdateModel the paymentobj1 values will be loss.

}
Posted

1 solution

When you post to your form the object is lost and all you have is a collection of key value pairs passed in from the web form. What you have to do is create a new object and try to map your form fields to your object. The TryUpdateModel method will do this for you if you created the web form correctly.

your code should look something like this:

C#
[HttpPost]
        public ActionResult Index(FormCollection formData)
        {
            Payment paymentobj1 = new Payment();

            // only allowing data from the form
            if (TryUpdateModel(paymentobj1 , formData))
            {
                
            }

            
        }
 
Share this answer
 
Comments
Anubhava Dimri 24-Oct-13 12:12pm    
Hi,

There is not any editor or View For ProductItems. but the values of ProductItems is assigned in the Constructor of Payment. So my question is that how can i get the values of ProductItems when i do't have editor or view for this section because i don't required ProductItems UI.

Thanks for reply.
Yuriy Loginov 24-Oct-13 13:50pm    
You can always assign them after the UpdateModel() runs. I suspect the UpdateModel() sets the value to null because it cant find any corresponding items in FormCollection.

Payment paymentobj1 = new Payment();
UpdateModel(paymentobj1);
paymentobj1.ProductItems = StaticClass.StaticMethod();


Another alternative may be to make the ProductItems list static.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900