We will create a new table, named "Contact", open the "androiddb.edmx" file, and right-click the "Update model from database." This is described in the front, not much here, so the "contact" class and its properties are created at the entity level. Next, we add a new controller class called "Contactcontroller" to display our message form and implement the message function. Let's look at the code in controller, as follows:
| The code is as follows |
Copy Code |
|
public class Contactcontroller:controller
{
Android.Models.AndroidEntities android = new Androidentities ();
//
Get:/contact/
Public ActionResult Create ()
{
return View ();
}
//
//POST:/contact/create
[HttpPost]
& nbsp; public ActionResult Create (contacts contact)
{
if (modelstate.isvalid)
{
Android. AddObject ("Contact", contacts);
Android. SaveChanges ();
return Redirecttoaction ("...). /home ");
}
Else
{
return View (Contact);
}
}
}
|
The above code is all the code needed in Controller, very concise, right? The 2 points to be explained are: 1. [Httppostattribute] indicates that the second method is executed only when the form submission is "Post", and in other cases the first create () method is executed. 2. We use the class ObjectContext method AddObject () method to add operations, parameters are property names and entities, Addtocontact () This method is now deprecated, which we need to pay attention to. For queries that use the Objectset property to refer to the following ASP.net MVC3 instance (iii) using Controller for data.
Next we add the view template to display the message form, right-click on the Create () method, add view, as shown below:
We have selected view data class as "contact", template for "Create", get the following view:
| The code is as follows |
Copy Code |
@model Android.Models.Contact
<body>
<script src= "@Url. Content (" ~/scripts/jquery-1.4.4.min.js ")" Type= "Text/javascript" ></script>
<script src= "@Url. Content (" ~/scripts/jquery.validate.min.js ")" Type= "Text/javascript" ></script>
<script src= "@Url. Content (" ~/scripts/jquery.validate.unobtrusive.min.js ")" Type= "Text/javascript" ></ Script>
@using (Html.BeginForm ()) {
@Html. ValidationSummary (True)
<fieldset>
<legend>Contact</legend>
<div class= "Editor-label" >
@Html. Labelfor (model => model. UserName)
</div>
<div class= "Editor-field" >
@Html. Textboxfor (model => model. UserName)
@Html. Validationmessagefor (model => model. UserName)
</div>
<div class= "Editor-label" >
@Html. Labelfor (model => model. Email)
</div>
<div class= "Editor-field" >
@Html. Textboxfor (model => model. Email)
@Html. Validationmessagefor (model => model. Email)
</div>
<div class= "Editor-label" >
@Html. Labelfor (model => model. Website)
</div>
<div class= "Editor-field" >
@Html. Textboxfor (model => model. Website)
@Html. Validationmessagefor (model => model. Website)
</div>
<div class= "Editor-label" >
@Html. Labelfor (model => model. Content)
</div>
<div class= "Editor-field" >
@Html. Textareafor (model => model. content,5,60, "Content")
@Html. Validationmessagefor (model => model. Content)
</div>
<p>
<input type= "Submit" value= "Create"/>
</p>
</fieldset>
}
</body> |
This type of writing is already available in ASP.net MVC 2, and there is not much to say, it uses a strongly typed HtmlHelper method to output the corresponding HTML markup. Read the message content there, we can define the size of the input box and ID (Name), very convenient. Here, we have completed the add operation in ASP.net MVC 3. When the user clicks the "Create" button, the data in the form is automatically assigned to the corresponding property.
We must always remember that "user input is evil" so that we need to validate the user's input. The improvement of solid layer data validation is also one of the highlights of MVC 3. @Html. ValidationSummary (True) indicates that we have enabled client-side asynchronous authentication, which obviously reduces unnecessary server requests, MVC3 Microsoft fully uses JQuery for client authentication.
The verification of the entity data in asp.net MVC3 is very simple, the business logic separates very well, such as when validating the message content, just add the following code:
| The code is as follows |
Copy Code |
[Required (errormessage= "cannot be empty")]
[Stringlength (1000, errormessage = "Length in 5-1000", Minimumlength = 5)]
Public global::system.string Content
{
Get
{
return _content;
}
Set
{
Oncontentchanging (value);
Reportpropertychanging ("Content");
_content = Structuralobject.setvalidvalue (value, true);
Reportpropertychanged ("Content");
Oncontentchanged ();
}
} |
The required and length two attributes were validated separately, and there were many attributes that we did not introduce. Finally look at the results, as follows:
Below let us on this basis to complete the ASP.net MVC3 modification and deletion operations.
First, we add a method named View () to the contact controller class to take the message data out of the Contact table and pass it to the list page "Index" as follows:
| code is as follows |
copy code |
//
//Get:/ contact/
Public ActionResult Index ()
{
var contacts = from C in Android. Contact
where c.isvalid = 1
by c.id Descending
Select C;
return View (contact. ToList ());
} |
We removed all valid data (isvalid==1) from the Contact table using Linq and displayed in descending order of ID. Next, add the view named "Index", and the final "index" code is as follows:
| The code is as follows |
Copy Code |
@model ilist<android.models.contact>
<p>
@Html. ActionLink ("Create New", "create")
</p>
<table>
<tr>
<th>
UserName
</th>
<th>
Content
</th>
<th>
Addtime
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@item. UserName
</td>
<td>
@item. Content
</td>
<td>
@item. Addtime
</td>
<td>
@Html. ActionLink ("editor", "edit", new {id=item.id}) |
@Html. ActionLink ("delete", "delete", new {id = item.id})
</td>
</tr>
}
</table> |
You can see that the display code is very neat, we do not do style landscaping, the final list page effect is as follows:
Modify operation, delete operation passed parameters are message ID, first of all, we look at the modification operation, respectively, to the "contact" Controller Add the name of Edit () two methods, 1. Used to get the message entity based on ID and return to the edit page; 2. Complete the modification operation. As follows:
| The code is as follows |
Copy Code |
|
//
//Get:/ CONTACT/EDIT/5
Public actionresult Edit (int id)
{
var message = Android. Contact.single (m => m.id = ID);
return View (message);
}
//
//POST:/CONTACT/EDIT/5
[HttpPost]
public actionresult Edit (int id, formcollection collectio N)
{
try
{
var Message = Android. Contact.single (m => m.id = ID);
updatemodel (message);
Android. SaveChanges ();
return redirecttoaction ("Index");//Back to list
}
catch
{
return View ();
}
} |
For brevity, we modify the message only if it is valid, and the others are similar, and the final code for the edit view is as follows:
| The code is as follows |
Copy Code |
|
@model Android.Models.Contact
@using (Html.BeginForm ()) {
<fieldset>
<legend>Contact</legend>
@Html. Hiddenfor (Model => model.id)
<div class= "Editor-label" >
@Html. Labelfor (Model=>model. Content, "message contents")
</div>
<div class= "Editor-field" >
@Model. Content
</div>
<div class= "Editor-label" >
@Html. Labelfor (model => model. IsValid, "valid")
</div>
<div class= "Editor-field" >
Effective @Html. Radiobuttonfor (Model=>model. isvalid,1)
Invalid @Html. Radiobuttonfor (Model=>model. isvalid,0)
</div>
<p>
<input type= "Submit" value= "Save"/>
</p>
</fieldset>
}
|
The effect of the page is as shown in the following illustration:
Where Radiobuttonfor is similar to the Labelfor usage method, when we click Edit in the list page, we first execute the first "edit" method and return the entity to our edit page based on the ID. When we click on "Save" to submit, we execute the second "Edit" method and modify the "contact" table in the database so that we have implemented the ASP.net MVC3 modification operation.
Below look at the delete operation, the Delete method in the "contact" Controller class uses only the Get method, because we will delete it directly based on the ID passed over, as follows:
| code is as follows |
copy code |
//
//Get:/ CONTACT/DELETE/5
Public actionresult Delete (int id)
{
try
{
& nbsp; var contact = Android. Contact.single (c => c.id = ID);
Android. DeleteObject (contact);
Android. SaveChanges ();
}
catch
{
}
return Redirecttoaction (".. /contact ");
} |
Of course, it's OK to have a "Delete" view completely empty at this point. The delete operation is returned to our message list, and the deletion is done. The use of the real deletion here is to illustrate the DeleteObject () method, in general this case we only need to modify the "IsValid" field to 0, do not really delete. It is also important to note that the example uses a try for exception handling, because a Linq query throws an exception if the corresponding exception, SaveChanges () is thrown when there is a problem.
From these two articles we are not difficult to find, in asp.net MVC3 we no longer need to manually write code to receive parameters, you can add, modify operations to see that we do not manually write code to receive the "Post" way to submit the form data. If you look at some of the MVC 3 articles are still using request["parameter"], request.form["parameter"], request.querystring["parameter"], collection[ "Parameter"] (collection is a FormCollection class object) to receive parameters, you need to pay attention to. Of course, there are a lot of features in ASP.net MVC3, and this series will be introduced.