我想将字符串变量传递给局部视图,但是我不确定如何将字符串参数显示给局部视图。我尝试了在类似问题上发现的一些答案,但得到以下输出:
“ my_app.Models.DogTreatments”。谁能告诉我为什么?
这是我的代码:
控制器:
[HttpPost]
public ActionResult CasIndex(int Sid)
{
string treat = dbContext.DogTreatments.Where(x => x.Sid == Sid).SingleOrDefault().ToString();
// ViewBag.TList = dbContext.DogTreatments.Where(x => x.Sid == Sid);
return PartialView("DisplayTreatments", treat);
}
查看页面:
@Html.Partial("~/Views/Shared/DisplayTreatments.cshtml")
部分视图:
@model string
@{
Layout = null;
}
@Model
最佳答案
由于您的LINQ语句,您看到的是正确的。
string treat = dbContext.DogTreatments.Where(x => x.Sid == Sid).SingleOrDefault().ToString();
此
dbContext.DogTreatments.Where(x => x.Sid == Sid)
过滤所有DogTreatments Where
x.Sid == Sid此
.SingleOrDefault()
选择类型为single object
或默认值(null)的DogTreatments
。toString()
将对象类型转换为其字符串格式,因此my_app.Models.DogTreatments
也许这可以满足您的要求:
从LINQ查询返回对象:
var treat = dbContext.DogTreatments.Where(x => x.Sid == Sid).SingleOrDefault();
return PartialView("DisplayTreatments", treat);
局部视图如下所示:
@using my_app.Models.DogTreatments //(this might need to be fixed)
@model DogTreatments
@{
Layout = null;
}
// in here you can access the DogTreatments object
// These are just examples as I don't know from question what DogTreatments properties are
@if(Model != null)
{
@Model.Name
@Model.Treatment
}