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

本文关键字:模型 属性 数据绑定 视图 | 更新日期: 2023-09-27 18:30:59

>我有一个具有这样属性的模型

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; } }

感谢您的帮助

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

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

控制器:

[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); });