ASP.NET : Model Binding in Razor Page
consoleGuy
1 min read
bila kita nak submit form dalam asp.net biasanya kita akan assign property dalam Model page macam ni
public string Title { get; set; }
public DateTime Tarikh{ get; set; }
public string Body { get; set; }
dan declare dalam OnPost() method
public void OnPost(string tajuk, string body, DateTime tarikh)
{
Tajuk = title;
Body= body;
Tarikh = tarikh
}
tapi bila buat macam ni, kita ada extra work sebab kena declare dalam OnPost()
so cara paling mudah ialah kita set BindProperty dalam Model Page macam ni
[BindProperty]
public string Title { get; set; }
[BindProperty]
public DateTime Date { get; set; }
[BindProperty]
public string Body { get; set; }
dan letak dalam form lebih kurang macam ni, yang penting value "id" kena sama macam yang kita assign dalam Model Page
<form method="post">
<div class="form-group">
<label for="Title">Title</label>
<input type="text" class="form-control" id="Title" name="Title" placeholder="Title">
</div>
<div class="form-group">
<label for="Date">Date</label>
<input type="date" class="form-control" id="Date" name="Date">
</div>
<div class="form-group">
<label for="Body">Your post</label>
<textarea class="form-control" id="Body" name="Body" rows="3"></textarea>
</div>
<button type="submit" class="btn" id="submit">Submit</button>
</form>
0
Subscribe to my newsletter
Read articles from consoleGuy directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by