如何通过控制器从模型访问数据?

时间:2014-04-14 07:01:00

标签: c# jquery asp.net ajax asp.net-mvc

我知道这似乎是一个简单的问题,但我相信viewbag是让我可以访问模型中的数据但是我想直接访问模型类而不是创建它的实例。我知道你可以通过使用模型类作为参数来使用主索引方法做到这一点,但是如何使用我创建的方法做同样的事情?

下面是我的代码,我正在尝试弄清楚如何将模型类作为参数传递,因此我调用的方法可以访问所有信息:

$(document).ready(function () {
        // if user changes paper type
        $('#paperTypeJList').change(function () {
        var value = $(this).val();

        $.ajax({
            url: '@Url.Action("getNewPrice","Home")',
            data: {dropdownValue:value, dropdownName: "paperType"},
            cache: false,
            async: true,
            success: function(response){
                alert(response);
            }
        });
    });

1 个答案:

答案 0 :(得分:1)

我很清楚你的问题。您也可以像这样调用您的方法

 [HttpPost]
 public JsonResult getNewPrice(EasyInfoModels model, string dropdownValue, string dropdownName )
{
    // do something with value and return a decimal
    if(string.IsNullOrEmpty(dropdownValue) && string.IsNullOrEmpty(dropdownName ))
     {
       //do something
       return Json(result)
     }
   else
    return Json("Blank");
}

和您的Ajax调用

var datas = {
       fullName :$("#fullname").val(),//retrieve the value from your model in the view
       email:"",//retrieve the value from your model in the view
       phone :"",//retrieve the value from your model in the view
       topic:"",//retrieve the value from your model in the view
       subject:"",//retrieve the value from your model in the view
       paperType:"",//retrieve the value from your model in the view
       urgency :"",//retrieve the value from your model in the view
       numOfPages :"",//retrieve the value from your model in the view
       requirements :"",//retrieve the value from your model in the view
       style:"",//retrieve the value from your model in the view
       spacing :"",//retrieve the value from your model in the view
       price :'',//retrieve the value from your model in the view
       dropdownValue:value, 
       dropdownName: "paperType"          
    };
  $.ajax({
        url: '@Url.Action("getNewPrice","Home")',
        type:"POST",
        data:datas ,
        contentType: "application/json; charset=utf-8",
        cache: false,
        async: true,
        success: function(response){
            alert(response);
        }
    });

希望它会对你有所帮助。 Binder将获取每个值来创建模型。