如何将视图数据绑定到模型属性

时间:2016-01-19 20:37:54

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

我有一个像这样的属性的模型

public class Category { public string statename { get; set; } }

我使用ajax从我的视图中获得了一个变量,如下所示

<script language="javascript"> function getlgass() {   var staname = $('#mylist option:selected').text();//this is a htmlhelper dropdownlist. i got the selected text from this list and saved it in that variable $.ajax({ url:'/Ministry/sendProp', type:'POST', data: JSON.stringify(staname), contentType: 'application/json; charset=utf-8', success: function (data) { alert(data.success); }, error: function(){alert("Error")} });// i'm posting it to my controller function using ajax $.getJSON('@Url.Action("getLGA","Ministry")', function (costs) { var $sel = $("#schLga"); $sel.empty(); $.each(costs, function (index, element) { $("<option/>").text(element).appendTo($sel); }); }); }   alert("something changed"); </script>

我需要将该变量传递给我的模型中的属性,以便我可以在函数getLGA中使用它来执行服务器请求 我的控制器功能如图所示

  [HttpPost] public ActionResult sendProp() { // i think i'm supposed to attach the value to my model property here, but i don't know how. return Json(new { success = true }); }   [AllowCrossSiteJson] public ActionResult getLGA() { try { Category c = new Category();   getMethods.getState(c); char[] chars = { ',' };   int statepos = c.Name.IndexOf(c.statename);//i need that value here string stateindex = c.ID.ElementAt(statepos).ToString();   testStealthServ.countries csd = new testStealthServ.countries(); List<string> sth = csd.getlocal(stateindex).ToList<string>(); foreach (var v in sth) { string[] splits = v.Split(chars);   c.lgaName.Add(splits.ElementAt(0)); c.lgaID.Add(splits.ElementAt(1)); }   return Json(c.lgaName, JsonRequestBehavior.AllowGet); } catch (Exception ex) { throw ex; } }

感谢您的协助

1 个答案:

答案 0 :(得分:0)

这里有一些术语没有按预期使用,但这里有一些你可以用来开始......

控制器:

[HttpPost]
public ActionResult sendProp(Category pModel) {
    //If you put a breakpoint here, pModel.statename will have the value from getlgass().
    string state = pModel.statename;
    return this.Json("success");
}

使用Javascript:

$.post('/ministry/sendProp', { statename: getlgass() }, function (data) { alert(data); });