0

My model looks like:

public class MyViewModel
    {
        public MyViewModel()
        {
            MyClasses = new List<MyClass>();
        }

        public List<MyClass> MyClasses{ get; set; }

        [Required(ErrorMessage = "is required.")]
        public string Prop1{ get; set; }

        [Required(ErrorMessage = "is required.")]
        public int Prop2{ get; set; }
    }

My controller on post:

[HttpPost]
public ActionResult MyActionOnPost(MyViewModel model)
{
//save to DB
//Prop2 is not null but Prop1 is nulll. why??
}

View code:

@Html.TextBoxFor(m => m.Prop2) @Html.ValidationMessageFor(m => m.Prop2)

@Html.TextBoxFor(m => m.Prop1) @Html.ValidationMessageFor(m => m.Prop1)

I can see Prop2 value on submit but Prop1 is null. Any idea?

2
  • 1
    I could see both the values on submit. I've tried with your viewmodel and textboxes as well Commented Feb 22, 2013 at 8:53
  • It is simple though don't see value. ModelState.IsValid is false. It says Prop1 is empty. Commented Feb 25, 2013 at 8:38

1 Answer 1

1

[DisplayFormat(ConvertEmptyStringToNull = false)]

This is your answer. Add this to every string in your code, and it will work perfectly!

Sign up to request clarification or add additional context in comments.

3 Comments

Add this just like you have added the Required tag. After adding it, you will get an empty string instead of null.
Sorry, why should I see empty or null when am typing in something?
Dear I guess you must have got null only when you posted empty Prop1 textbox. If you fill the textbox with some value and then post it, I am sure you will get it on the server-side. I am not sure about your problem, are you getting null even if you fill some value in textbox?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.