我无法使用MongoDB csharp官方库获取模型的ObjectId以返回值。当我提交回发到控制器的表单时,PageID总是在模型中返回{000000000000000000000000}。呈现的HTML具有有效的id,即一个字段永远不会从表单帖子中正确返回。
html呈现:<input id="PageID" name="PageID" type="hidden" value="4f83b5ccd79f660b881887a3" />
这就是我所拥有的。
型号:
public class PageModel
{
public PageModel()
{
CanEdit = false;
CancelRequest = false;
}
[BsonId]
public ObjectId PageID { get; set; }
[Display(Name = "Page URL")]
public string PageURL { get; set; }
[AllowHtml]
[Display(Name = "Content")]
public string Value { get; set; }
[Display(Name = "Last Modified")]
public DateTime LastModified { get; set; }
[BsonIgnore]
public bool CancelRequest { get; set; }
[BsonIgnore]
public bool CanEdit { get; set; }
}
控制器帖子:
[HttpPost]
public ActionResult Edit(PageModel model)
{
// check to see if the user canceled
if (model.CancelRequest)
{
return Redirect(model.PageURL);
}
// check for a script tag to prevent
if (!model.Value.Contains("<script"))
{
// save to the database
model.LastModified = DateTime.Now;
collection.Save(model);
// return to the page
return Redirect(model.PageURL);
}
else
{
ModelState.AddModelError("Value", "Disclosures discovered a script in the html you submitted, please remove the script before saving.");
}
return View(model);
}
查看:
@model LeulyHome.Models.PageModel
@{
ViewBag.Title = "";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm())
{
<fieldset>
<legend>Edit Page</legend>
<div class="control-group">
@Html.LabelFor(m => m.PageURL, new { @class = "control-label" })
<div class="controls">
@Html.TextBoxFor(m => m.PageURL, new { @class = "input-xlarge leu-required span9" })
@Html.ValidationMessageFor(m => m.PageURL, null, new { @class = "help-block" })
</div>
</div>
<div class="control-group">
@Html.LabelFor(m => m.Value, new { @class = "control-label" })
<div class="controls">
@Html.TextAreaFor(m => m.Value)
@Html.ValidationMessageFor(m => m.Value, null, new { @class = "help-block" })
</div>
</div>
<div class="control-group">
@Html.LabelFor(m => m.LastModified, new { @class = "control-label" })
<div class="controls">
@Html.DisplayFor(m => m.LastModified)
@Html.HiddenFor(m => m.LastModified)
</div>
</div>
@Html.HiddenFor(m => m.PageID)
@Html.HiddenFor(m => m.CancelRequest)
<div class="form-actions">
<button type="submit" class="btn btn-primary">Save Page</button>
<button type="button" class="btn btn-danger" id="cancelBtn">Cancel Changes</button>
</div>
</fieldset>
}
@section Footer {
<script type="text/javascript" src="@Url.Content("~/Content/ckeditor/ckeditor.js")"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
// adjust the editor's toolbar
CKEDITOR.replace('Value', {
toolbar: [["Bold", "Italic", "Underline", "-", "NumberedList", "BulletedList", "-", "Link", "Unlink"],
["JustifyLeft", "JustifyCenter", "JustifyRight", "JustifyBlock"],
["Cut", "Copy", "Paste", "PasteText", "PasteFromWord", "-", "Print", "SpellChecker", "Scayt"], ["Source", "About"]]
});
$("#cancelBtn").click(function () {
$("#CancelRequest").val("True");
$("#updateBtn").click();
});
});
</script>
}
答案 0 :(得分:2)
看起来您正在为PageID发送一个字符串值,您希望它是ObjectId类型的对象。
模型绑定不会知道如何获取此字符串并将其转换为ObjectId。如果你看一下MongoDriver中的ObjectId类,你会发现它非常多毛。
我们使用mongodb很多,对于我们的id,我们只使用提供很大灵活性的字符串。我不确定您需要将ObjectId类作为文档ID的用例,但您可能不需要它。
所以从这里看起来你有两个选择。
希望有所帮助:)
答案 1 :(得分:1)
创建绑定:
public class ObjectIdBinder:IModelBinder {
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
return !string.IsNullOrWhiteSpace(result.AttemptedValue) ? ObjectId.Parse(result.AttemptedValue) : ObjectId.Empty;
}
}
创建ModelBinderConfig:
命名空间Nasa8x.CMS { 公共类ModelBinderConfig { public static void Register(ModelBinderDictionary binder) { binder.Add(typeof(ObjectId),new ObjectIdBinder());
binder.Add(typeof(string[]), new StringArrayBinder());
binder.Add(typeof(int[]), new IntArrayBinder());
}
}
}
在Global.cs上注册:
protected void Application_Start()
{
ModelBinderConfig.Register(ModelBinders.Binders);
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
答案 2 :(得分:1)
If you don't need the PageID property in your C# Class to be of Type ObjectId, but want to take advantage of this Type on the MongoDB-Side, you can let the Driver take care of the conversion in your class-Definition:
public class PageModel
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string PageID { get; set; }
}