Rodrigo A.
Rodrigo A.

Reputation: 13

How to get Model value in javascript function and pass it to controller?

I have a Model on my CSHTML page that which I use this way:

@model Web.Models.Element

@using (Html.BeginForm("Search", "Company"))
{
@Html.HiddenFor(c => c.Person)

<div class="panel panel-default">
    <div class="panel-heading"> Company Search</div>
    <div class="panel-body collapse" id="screenCompanySearch">
        <form id="formSearch" name="formSearch" method="post">
            <fieldset style="margin: 20px;">
                <legend>Search</legend>

                <div class="row">
                    <div class="col-xs-2 col-sm-2">
                        @Html.Label("Company Name")
                        @Html.TextBoxFor(c => c.Company.Name, new { @class = "form-control" })
                    </div>
           </fieldset>
        </form>
    </div>
</div>

My Javascript function is called by a button click this way:

$("#btnSearch").on("click", function() { searchCompany(); })'

In my JavaScript function I need to get this Model entirely loaded with the TextBoxFor values:

<script type="text/javascript">
function searchCompany() {
   var data = $("#formSearch").serialize();
    $.ajax({
        url: "@(Url.Action("SearchCompany", "Company"))",
        cache: false,
        data: data,
        type: "POST",
        success: alert("sucesso!")
    });
}
</script>

My Controller method is being loaded correctly, but the model passed in the Ajax "data" parameter is not filled with the TextBoxFor values.

This is my Controller ActionResult for the View:

public ActionResult Consulta()
    {
        Element model = new Element();
        model.Person = new Person();

        return View(model);
    }

What is happening is that my Model is being instantiated on my Controller but the values from the TextBoxFor is not recorded on the properties of the Model.

How can I solve this? Thanks for now.

UPDATED

<div class="col-xs-2 col-sm-2">
     @Html.Label("Person Name")
     @Html.TextBoxFor(c => c.Person.Name, new { @class = "form-control" })
</div>

So, 'c' equals my Element object. When I reach the Controller Method "Search", the parameter Element passed via ajax call does not instantiate the Element.Person which gives me Person = null.

In my ActionResult I have:

Element model = new Element();
model.Person = new Person();

Element class:

public Element()
{
    this.Contacts = new List<Contact>();
    this.DataType = new DataType();

}

public int ID_Element { get; set; }
public int ID_ElementType { get; set; }

public virtual List<Contact> Contacts { get; set; }
public virtual DataType DataType { get; set; }
public virtual Person Person {get; set; }

Controller Action

[HttpPost]
public JsonResult SearchCompany(Element model)
{
    ...
}

Upvotes: 1

Views: 3060

Answers (1)

Shyju
Shyju

Reputation: 218722

The serialize method is not giving your the serialized version of the form because you have nested form tags.

The @using (Html.BeginForm("Search", "Company")) will create an outer form tag and you have your other form inside that, hence creating a nested form structure. Nested forms are invalid. You can have 2 forms in the same page, parallel to each other, not nested.

If you fix the nested form issue, the serialize method will give you valid string for you form inputs.

@using (Html.BeginForm("Search", "Company"))
{
   <!-- Your other form -->
}

<form id="formSearch" name="formSearch" method="post">
    <fieldset style="margin: 20px;">
        <legend>Search</legend>

        <div class="col-xs-2 col-sm-2">
            @Html.Label("Company Name")
            @Html.TextBoxFor(c => c.Company.Name, new { @class = "form-control" })
        </div>
    </fieldset>
</form>

Keep in mind that, the serialize method will give you the input element values of items inside this specific form. If you want to send some other data (ex : Id), you need to keep that in an input field inside this form.

Upvotes: 1

Related Questions