【问题标题】:how to pass variable to property of model in mvc如何将变量传递给mvc中模型的属性
【发布时间】:2017-04-20 23:49:56
【问题描述】:

我有一个模型如下:

public  class Class1
{
    public int Id { get; set; }
    public DateTime Start { get; set; }
} 

我有一个ActionResult,它是这样的:

public ActionResult Create(Class1 model)
{
    ...
} 

现在,我想使用 ajax 从另一个外部 javascript 文件中填充 Start 属性,如下所示:

$.ajax({
    url: "/Admin/Create",
    dataType: "Json",
    type: "Post",
    data: Start:"..."
});

如何访问另一个 View TextBox 并使用 ajax 填充它? ajax上的数据应该怎么做?

【问题讨论】:

  • data: { Start: $(yourTextBox).val() },
  • @StephenMuecke 感谢您的回复,但在ActionResult 中得到model。我怎样才能访问模型property
  • @mojtaba1390 model.Start ..
  • 抱歉,我不确定我是否理解您的评论 - 如果文本框的值是(比如说)2016 年 12 月 6 日,那么 model.Start 将是 2016 年 12 月 6 日

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


【解决方案1】:

请尝试以下代码:-

var model = { Name :"Shyju", 
              Location:"Detroit", 
              Interests : ["Code","Coffee","Stackoverflow"]
            };

$.ajax({
    type: "POST",
    data: JSON.stringify(model),
    url: url,
    contentType: "application/json"
}).done(function (res) {
    $("#SomeDivToShowTheResult").html(res);
});



public class DashboardViewModel
{
  public string Name {set;get;}
  public string Location {set;get;}
  public List<string> Interests {set;get;}
}


[HttpPost]
public PartialViewResult IndexPartial([FromBody] DashboardViewModel m)
{
    return PartialView("_IndexPartial",m);
}

【讨论】:

  • 这段代码到底和OP的问题有什么关系
猜你喜欢
  • 2020-01-09
  • 2020-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-21
  • 1970-01-01
  • 2015-12-23
相关资源
最近更新 更多