1

I am using a post method, where i am trying to post the value of textbox to database, for this i am doing all the necessary steps, but in that post method my model is null. Find the code below, My Simple Controller

 [HttpPost]
    public ActionResult Index(QuestionBankModel question)
    {
        return View();
    }

My Model

public class QuestionBankModel
    {
        public string question { get; set; }
    }

My View

@model OnlinePariksha.Models.QuestionBankModel
@{
    var CustomerInfo = (OnlinePariksha.Models.UserLoginModel)Session["UserInfo"];
}
@{
    ViewBag.Title = "Index";
}
@{
    Layout = "~/Views/Shared/Admin.cshtml";
}
@using (Html.BeginForm("Index", "AdminDashboard", FormMethod.Post))
{
<div id="questionsDiv" style="width:100%; display:none;">
    <div style="width:200px">
        <table style="width:100%">
            <tr>
                <td><span><b>Question:</b></span></td>
                <td>
                    @Html.TextBox(Model.question, new Dictionary<string, object> { { "class", "textboxUploadField" } })
                </td>
            </tr>

        </table>
    </div>
    <div class="clear"></div>
    <div>
        <input type="submit" class="sucessBtn1" value="Save" />
    </div>
</div>
}

Did i miss anything?

1
  • So the QuestionBankModel has 1 property: question. And upon hitting the Index action on HttpPost, that question's value is null? Commented Jan 15, 2015 at 20:33

3 Answers 3

2

Your problem is that the POST method parameter name is the same name as your model property (and as a result model binding fails). Change the method signature to

public ActionResult Index(QuestionBankModel model)
{
  ...
}

or any other parameter name that is not the same as a model property.

By way of explanation, the DefaultModelBinder first initializes a new instance of QuestionBankModel. It then inspects the form (and other) values and sees question="SomeStringYouEntered". It then searches for a property named question (in order to set its value). The first one it finds is your method parameter so it internally it does QuestionBankModel question = "SomeStringYouEntered"; which fails (you cant assign a strung to a complex object) and the model parameter now becomes null.

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

Comments

0

Html.TextBox is being used incorrectly because the first parameter is the name of the textbox and you're passing the value of question. I would use this instead:

@Html.TextBoxFor(m => m.question)

Comments

0

Have you tried using @HTML.TextBoxFor?

@Html.TextBoxFor(m=>m.question,new Dictionary<string, object> { { "class", "textboxUploadField" } })

1 Comment

How about try typing something into the textbox, then click "Submit"?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.