How to auto populate a textbox in mvc
I have a simple from that a user will complete to submit a "newswire". When the form loads on the create view I want the author Input to auto populate with the logged in username inside the text box in the view. Can anyone comment on what I'm doing wrong?
my model:
public class NewsWire
{
public int ID { get; set; }
public int VendorID { get; set; }
public DateTime Date { get; set; }
public string Subject { get; set; }
public string NewsItem { get; set; }
//public string Author { get; set; }
public string Author
{
get
{
return System.Web.HttpContext.Current.User.Identity.Name;
}
}
}
In the form for the author section I have this:
<div class="editor-label">
@Html.L开发者_如何学JAVAabelFor(model => model.Author)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Author)
@Html.ValidationMessageFor(model => model.Author)
</div>
I have tried several variations but still not getting it right. Any help would be appreciated.
Model:
public class NewsWire
{
public int ID { get; set; }
public int VendorID { get; set; }
public DateTime Date { get; set; }
public string Subject { get; set; }
public string NewsItem { get; set; }
public string Author { get; set; }
}
and inside the controller action that renders this view populate the Author
property from the currently logged in user:
[Authorize]
public ActionResult SomeAction()
{
var model = new NewsWire
{
Author = User.Identity.Name
};
return View(model);
}
OK, something I've noticed is that you're creating an Editor, but the Author only has a { get; } in the model. That could be a problem!
You should keep it as a property, but populate Author when you initialise the object.
精彩评论