【问题标题】:How to bind view data to model properties [closed]如何将视图数据绑定到模型属性 [关闭]
【发布时间】:2016-04-25 11:59:13
【问题描述】:

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

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

感谢您的帮助

【问题讨论】:

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


    【解决方案1】:

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

    控制器:

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

    【讨论】:

    • 请我不明白你所说的填充是什么意思你的意思是我应该这样做 pModel.statename = //something 吗?这就是我想念的重点。
    • 不,我的意思是由于在发布数据中使用了 statename:,因此 MVC 系统将在控制器开始处理之前为您填充该值。我无法从问题中判断您是否有兴趣发布数据或从服务器检索数据以显示。
    • 我有兴趣从视图的下拉框中检索数据并在控制器功能中使用它。所以我想,如果我可以在模型中创建一个属性来保存该值,那么我可以从控制器函数 getLGA() 中检索该值并在那里使用它
    • 我更新了我的答案。希望它现在会更有帮助。有一些魔法在继续。您可能需要尝试此示例代码并在调试器中逐步完成。
    猜你喜欢
    • 1970-01-01
    • 2010-09-27
    • 2010-12-02
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多