Adan Ramirez Adan Ramirez - 3 months ago 14
jQuery Question

Simplest way to get model data/objects in the view from input with an ajax partial view call(s)

Hello i googled to find a solution to my problem, every link brought me to asp forms solution, or solutions that do not ask for form inputs, this problem has form inputs and i cant seem too find a link for help, what im asking for is simple: get the data from user input through models by ajax calls.

View (index.cshtml):

@model UIPractice.Models.ModelVariables

<!-- Use your own js file, etc.-->
<script src="~/Scripts/jquery-1.10.2.js" type="text/javascript"></script>

<div id="div1">

@Html.BeginForm(){ @Html.TextBoxFor(x => x.test1, new { style = "width:30px" })}




<button id="hello"></button>
</div>

<div id="result1"></div>

<script type="text/javascript">

//Job is to load partial view on click along with model's objects
$(document).ready(function () {
$('#hello').click(function () {

$.ajax({
type: 'POST',
url: '@Url.Action("HelloAjax", "Home")',
data: $('form').serialize(),
success: function (result) {
$('#result1').html(result);
}

});
});
});




Model (ModelVariables.cs):

public class ModelVariables
{
//simple string that holds the users text input
public string test1 { get; set; }

}


Controller (HomeController.cs):

// GET: Home
public ActionResult Index()
{
ModelVariables model = new ModelVariables();
return View(model);
}

public ActionResult HelloAjax(ModelVariables model)
{


ViewBag.One = model.test1;`
return PartialView("_MPartial", model);
}


Partial View (_MPartial.cshtml):

@model UIPractice.Models.ModelVariables



@{
<div>
<!--if code runs, i get a blank answer, odd...-->
@Model.test1
@ViewBag.One
</div>
}


So go ahead and copy/paste code to run, you will notice that you get nothing when you click the button, with user text input, odd...

Answer

I see a few problems.

Your code which use the Html.BeginForm is incorrect. It should be

@using(Html.BeginForm())
{ 
   @Html.TextBoxFor(x => x.test1, new { style = "width:30px" })
   <button id="hello">Send</button>
}
<div id="result1"></div>

This will generate the correct form tag.

Now for the javascript part, you need to prevent the default form submit behavior since you are doing an ajax call. You can use the jQuery preventDefault method for that.

$(document).ready(function () {
    $('#hello').click(function (e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '@Url.Action("HelloAjax", "Home")',
            data: $('form').serialize(),
            success: function (result) {
                $('#result1').html(result);
            } 
            ,error: function (a, b, c) {                     
                    alert("Error in server method-"+c);
            }

        });
    });
});

Also, you might consider adding your page level jquery event handlers inside the scripts section (Assuming you have a section called "scripts" which is being invoked in the layout with a "RenderSection" call after jQyery is loaded.

So in your layout

<script src="~/PathToJQueryOrAnyOtherLibraryWhichThePageLevelScriptUsesHere"></script>
@RenderSection("scripts", required: false)

and in your indidual views,

@section scripts
{
  <script>
  //console.log("This will be executed only after jQuery is loaded
  $(function(){
       //your code goes here
  });
  </script>
}
Comments