1

All I wanted to do is do an $.ajax() post back when a user goes from step 2 to step 3 in smart wizard. So i worked out the following code. I have used var model = JSON.stringify(@Model); to convert my model to string and pass it using ajax request

Ajax code

 var model = JSON.stringify(@Model);
                var s = 10;
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("GetSampleFeed")',
                    data: "inStringModel=" + model
                });

but the above does not fire an call back to the controller. I have checked by removing the JSON.stringify(@Model) and replaced it by "Just text". Now the ajax request reaches the controller with out any issues

Below are my codes

Model File

public class OndemandFeedModel
{
    /// <summary>
    /// Collection of countrt that the application supports
    /// </summary>
    public CountryModel Country { get; set; }

    /// <summary>
    /// Model used to display fields and retrive the selected fields from user
    /// </summary>
    public FieldSelectModel Fields { get; set; }

    /// <summary>
    /// Model used to display filters and retrive the selected fields from user
    /// </summary>
    public FilterSelectModel Filters { get; set; }
}

public class FieldSelectModel
{


    /// <summary>
    /// Collection of Fields
    /// </summary>
    public List<FieldGroup> FieldGroup { get; set; }
}

public class FilterSelectModel
{
    [Required]
    [Display(Name="From")]
    public DateTime StartTime { get; set; }

    [Required]
    [Display(Name="To")]
    public DateTime EndTime { get; set; }

    public FilterSelectModel()
    {
        StartTime = DateTime.Now;
    }
}

public class FieldGroup
{
    /// <summary>
    /// group of the field
    /// </summary>
    public string GroupName { get; set; }

    /// <summary>
    /// group of the field
    /// </summary>
    public List<FieldModel> Fields { get; set; }
}

public class FieldModel
{
    /// <summary>
    /// Unique Id referred to each field
    /// </summary>
    public int FieldId { get; set; }

    /// <summary>
    /// name of the field
    /// </summary>
    public string FieldName { get; set; }

    /// <summary>
    /// user defined name for the field
    /// </summary>
    public string UserDefinedFieldName { get; set; }

    /// <summary>
    /// bool value indicating whether the field has been selected by the user
    /// </summary>
    public bool IsEdited { get; set; }

    /// <summary>
    /// type of the field coded / raw
    /// </summary>
    public string FieldType { get; set; }

    /// <summary>
    /// category of the field in which it has been clasified
    /// </summary>
    public string FieldGroup { get; set; }

    /// <summary>
    /// status of the field if status is 1 display field to user other wise dont display
    /// </summary>
    public int Status { get; set; }

    /// <summary>
    /// country of field
    /// </summary>
    public string Country { get; set; }

    /// <summary>
    /// Title attribute for the element will be poped up in tool tip
    /// </summary>
    public string Title { get; set; }

    public FieldModel()
    {
        IsEdited = false;
        UserDefinedFieldName = string.Empty;
        Title = "Double click each fields to edit.";
    }
}

My View

My Javascript code

<script type="text/javascript">

    $(document).ready(function () {
        $('#wizard').smartWizard({
            onShowStep: showAStepCallback,
            onFinish: onFinishCallback
        });

        function showAStepCallback(obj, context) {

            if (context.fromStep == 2 && context.toStep == 3) {
                var model = JSON.stringify(@Model);
                var s = 10;
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("GetSampleFeed")',
                    data: "inStringModel=" + model
                });

            }

            // return false to stay on step and true to continue navigation 
        }
        // setting the active tab
        $('#wizard').smartWizard();
        $('.date').datepicker({ dateFormat: "dd/mm/yy" });
        function onFinishCallback() {
            $('#wizard').smartWizard('showMessage', 'Finish Clicked');
            //alert('Finish Clicked');
        }
            .....
    });
</script>

Controller code

[HttpPost]
public ActionResult GetSampleFeed(string inStringModel)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    var inObjectModel = serializer.Deserialize(inStringModel, typeof(OndemandFeedModel));
    return Content("<row></row>");
}

Any help will be much appreciated !!

Thanks

Update 1

I have changed the

var model = JSON.stringify(@Model);

to

var model = @{new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model);}            

now the request reaches controller but the model i received is empty.

Umamaheswaran
  • 3,690
  • 3
  • 29
  • 56

1 Answers1

0

JSON.stringify(@Model); isn't going to do what you think it's going to do. JSON.stringify expects a Javascript object. @Model is going to have Razor output the contents of Model.ToString();, which will not be a Javascript object.

You need to serialize your model to Javascript, which you can do using the JavaScriptSerializer:

var model = @{new JavaScriptSerializer().Serialize(Model)};
                var s = 10;
                $.ajax({
                    type: 'POST',
                    url: '@Url.Action("GetSampleFeed")',
                    data: model
                });

You can find the JavaScriptSerializer in the System.Web.Extensions DLL.

Also, since you are deserializing your model, you do not need to convert it to/from JSON. MVC and jQuery will handle this for you, so on your controller side you can do:

[HttpPost]
public ActionResult GetSampleFeed(OndemandFeedModel model)
{
    return Content(string.Format("<row>{0}</row>", model.RowName));
}
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • Hi Blade, Thanks for the reply. I have tried as you have suggested now the request reaches controller but i have received an empty model. – Umamaheswaran Jul 23 '13 at 07:49
  • @Umamaheswaran Use either Chrome console/Firefox Firebug to check exactly what data is sent to the server. You may need to change some parameters to make sure MVC recognises it as JSON. See this answer: http://stackoverflow.com/questions/4120212/mvc-ajax-json-post-to-controller-action-method – CodingIntrigue Jul 23 '13 at 07:51