JQuery中[Model]类型对象的访问属性

Access property of an object of type [Model] in JQuery

本文关键字:对象 访问 属性 类型 Model JQuery      更新时间:2023-09-26

所以在我的MVC项目中,我有一个名为Survey的自定义模型,它包含一些属性。在调查控制器中,我将调查保存到一个会话变量中,以便调查属性的值在每个会话中持久化。

我希望能够根据会话调查的属性值来操作视图的DOM。但是我不知道如何访问它们。

我确实发现了这个相对较新的问题,似乎非常相似,但没有答案:无法访问javascript模型的属性

这是我到目前为止所做的:在视图中,我得到会话的调查如下:

     <input type="hidden" name="activeS" value="@HttpContext.Current.Session("Survey")" />

然后在底部的Section Scripts中,我有这个脚本来获取该值并对其进行操作:

 @Section Scripts
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
    $(function () {
        var survey = $("[name=activeS]").val();
        $("[name=mddbccu][value=" + survey.mddbccu + "]").prop('checked', true);
    })
</script>
 End Section

如果我在"var survey…"后面插入"alert(survey);"它会给我一个警告,显示调查对象的类型。看起来调查结果恢复得很好。但如果我尝试"alert(survey.mddbccu);",警报就会显示"undefined"。

请注意,在那之后的行("$([name=mddbccu]…")我知道工作-之前设置一个变量为特定的值,使用适当的项目进行检查。但是,在试图获得调查的这个特定属性的值时,没有检查任何内容。

我如何得到调查的属性值呢?谢谢你!

您的方法可以使用一些黑客和变通方法,但它不符合MVC的精神。下面是如何用MVC的方式完成它。基本上,您将所有繁重的工作(解析会话中的项)移到控制器中,并将结果存储在ViewModel中。这使逻辑脱离了视图,使代码更清晰,更易于维护。

如果你有一个ViewModel:

public ActionResult Survey()
{
    SurveyViewModel model = new SurveyViewModel();
    Survey surveySession = HttpContext.Current.Session("Survey") as Survey; // youll have to do extra null checks and such here
    // map other properties from the survey object retrieved from the session to your viewmodel here!
    model.mddbccu = surveySession.mddbccu;
    model.otherProperty = surveySession.otherProperty
    return View(model);
}

如果你只是使用Survey对象作为视图内的模型,那就更简单了:

public ActionResult Survey()
{
    Survey model = HttpContext.Current.Session("Survey") as Survey;
    return View(model);
}

然后,MVC根据你在控制器中设置的内容神奇地为你选择内容。如果您使用的是@RadioButtonFor(m => m.mddbccu, "three"),则如果将值"three"放入控制器的mddbccu属性中,则选中单选。