Search code examples
asp.net-mvc-4getjson

JQuery getJSON is not working in MVC4 Project


I don't know what I need to do in MVC4 Project. It is worked fine in MVC3 project.

I tried to call controller method to get Json Result. I want to show First Name and Last Name after input UserName at client. I used getJson to get Json from controller class. It was working find in mvc3 project but after I moved to MVC4 JQuery Method is not running.

My Controller:

public JsonResult PopulateDetails(EditUserModel model)
    {
        EditUserModel userResultModel = new EditUserModel();

        userResultModel.LastName = "John";
        userResultModel.FirstName = "Marry";


        return Json(userResultModel, JsonRequestBehavior.AllowGet);
    }

My View:

<script type="text/javascript">



function PopulateData() {
        var user = {};
        user.UserName = $("#UserName").val();
        $.getJSON("PopulateDetails", user, updateFields);   // Call the Function from Controller

    };

    updateFields = function (data) {


        $("#FirstName").val(data.FirstName);
        $("#LastName").val(data.LastName);

    };

<div class="editor-field">
        @*@Html.EditorFor(model => model.UserName)*@
         @Html.TextBoxFor(model => model.UserName, new { tabindex = "1", onblur = "javascript:PopulateData();"  } )
        @Html.ValidationMessageFor(model => model.UserName)
    </div>

 <div class="editor-label">
        @Html.LabelFor(model => model.FirstName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.LastName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)
    </div>

Pls let me know what is wrong in MVC4 Project.

Thanks..


Solution

  • I put all my scripts into

    @section Scripts { 
    
               <script type="text/JavaScript"> {  // My Function  } }
    

    then worked for me.