Search code examples
c#asp.net-mvc-4postsubmithtml.textboxfor

MVC 4 submit button doesn' t post texboxfor<> values to [httppost] method


when i click submit button in my actionresult get invoked but parameters are all empty in model which is models.Soru named as form.

it sends all properties like in my Soru() constructer. Empty string or 0 if int. textboxfor<> cant post values even i edit textbox values on view.

does anyone have idea?

public class Soru
{
    public int ID;
    public string Ad;
    public string SoruIcerik;
    public string Cevap;
    public int Sira;

    public Soru()
    {
        ID = 0;
        Ad = string.Empty;
        SoruIcerik = string.Empty;
        Cevap = string.Empty;
        Sira = 0;
    }
}

//here is controller

    [ValidateInput(false)]
    [HttpPost]
    public ActionResult Index(Models.Soru form)
    {

        return null;
    }

// and view

@model X.Models.Soru
@{


using (Html.BeginForm())
{
    <div class="col-md-7">

        @Html.TextAreaFor(m => m.SoruIcerik, new { @name = "soruIcerik", @id = "soruIcerik", @rows = "10", @cols = "80" })

    </div>
    <div class="col-md-5">
        <div class="col-md-4 formSatiri">
            <label class="formSatiri">
                Soru Adi :
            </label>
        </div>
        <div class="col-md-8">
            @Html.TextBoxFor(m=>m.Ad, new { @class = "formSatiri" })
        </div>
        <div class="col-md-4 formSatiri">
            <label class="formSatiri">
                Cevap :
            </label>
        </div>
        <div class="col-md-8">
            @Html.TextBoxFor(m => m.Cevap, new { @class = "formSatiri" })
            </div>
        <div class="col-md-12 formSatiri">
            <input type="submit" class="btn btn-primary btn-sm pull-left" value="Kaydet"/>
        </div>
    </div>
}

}

Solution

  • You have written the wrong syntax here:

    @Html.TextAreaFor(m => m.SoruIcerik, new { @name = "soruIcerik", @id = "soruIcerik", @rows = "10", @cols = "80" })
    

    which should be like this:

    @Html.TextAreaFor(m => m.SoruIcerik, new { @name = "SoruIcerik", @id = "SoruIcerik", @rows = "10", @cols = "80" })
    

    name and id was "soruIcerik" which must match to the property name "SoruIcerik".

    Or you can simply write like this:

    @Html.TextAreaFor(m => m.SoruIcerik, new {@rows = "10", @cols = "80" })
    

    The control will render in html something like this:

    <textarea id="SoruIcerik" name="SoruIcerik" rows="10" cols="80"></textarea>
    

    Here name and id must be the same as property defined in the model.

    You need to make the class variables as Properties. Like:

    public class Soru
    {
        public int ID {get;set};
        public string Ad {get;set};
        public string SoruIcerik {get;set};
        public string Cevap {get;set};
        public int Sira {get;set};
    }