20 secrets of mvc3-(14) Using ajax to submit form

Source: Internet
Author: User
Tags actionlink

Problem

You have a webpage that lists important information details. You need to allow users to submit a form quickly and easily without re-loading the entire page and losing their location on the website.

Solution

Use ajaxhelper to create a new form and automatically update the existing content with the newly submitted content.

Discussion

The example below puts the previous recipe together to show people how to ask users to submit comments of a book, instead of redirecting them to another page to view those comments and comments submitted by themselves.

First, we need to create a new model to store comments to books. In the model folder, right-click and choose "add"> "class", and name it bookcomment. CS. This model will be used to store comments on books.CodeAs follows:

 Using System;
Using System. Collections. Generic;
Using System. componentmodel. dataannotations;
Using System. LINQ;
Using System. Web;

Namespace Mvcapplication. Models
{
Public Class Bookcomment
{
Public Int Id { Get ; Set ;}
[Required]
Public String Comment { Get ; Set ;}
Public Datetime created {Get ; Set ;}
Public Int Bookid { Get ; Set ;}
Public Virtual Book { Get ; Set ;}
}
}

Next, you must update the previously created bookdbcontext to add a reference to the table. The previous class was created on the original bookmodel. Therefore, it is wise to create a new file to store this class. Because it will continue to grow with the tables in your project and in the future. Right-click the models folder. Again, select Add> class. The class name will be bookdbcontext:

(TRANSLATOR: do not forget to delete your bookdbcontext in the book model !)

UsingSystem;
UsingSystem. Collections. Generic;
UsingSystem. Data. entity;
UsingSystem. LINQ;
UsingSystem. Web;

NamespaceMvcapplication. Models
{
Public ClassBookdbcontext: dbcontext
{
PublicDbset <book> books {Get;Set;}
PublicDbset <bookcomment> bookcomments {Get;Set;}
}
}

Next, build your solution again. In the following steps, you can find our new model.

We need to create a new controller to implement the comment list and have the ability to manage them. Select the Controller folder and click "add"> "controller". Name it bookcommentscontroller. CS. To minimize manual work. We will useEntity FrameworkScaffolding creates a controller. For data context class, selectBookdbcontext. (TRANSLATOR: modle class selection: bookcomment (mvcapplication. Models )). Click Add. When you run the application againProgramYou will receive an error indicating that the bookdbcontext has changed. To solve this problem, you must create an initializer for dbcontext ). Because this is not a production environment application, the initialization will delete and recreate the database. To achieve this, right-click the models folder. Select Add> class and name it bookinitializer. The Code is as follows:

 

UsingSystem;

UsingSystem. Collections. Generic;

UsingSystem. Data. entity;

UsingSystem. LINQ;

UsingSystem. Web;



NamespaceMvcapplication. Models

{

Public ClassBookinitializer: dropcreatedatabaseifmodelchanges <bookdbcontext>

{

}

}

Next, global. asax. CS will be updated. Call bookinitializer in application_start. The method for updating application_start is as follows:

Protected VoidApplication_start ()
{
Database. setinitializer <bookdbcontext> (NewBookinitializer ());
Arearegistration. registerallareas ();

Registerglobalfilters (globalfilters. filters );
Registerroutes (routetable. routes );
}

Now that the configuration is complete, we need to allow users to submit a comment through Ajax. We will start with book/Details View, because most of the logic for displaying comments is here. (TRANSLATOR: because the original book references a lot of code, I only pointed out the code we changed here ). The Code is as follows:

@ Model mvcapplication. Models. Book
@{
Viewbag. Title = " Details " ;
}
<H2>
Details </H2>
<Fieldset>
<Legend> book </legend>
<Div Class = " Display-label " >
Title </div>
<Div Class = " Display-field " >
@ Html. displayfor (model => model. Title)
</Div>
<Div Class = " Display-label " >
ISBN </div>
<Div Class = " Display-field " >
@ Html. displayfor (model => model. ISBN)
</Div>
<Div Class = " Display-label " >
Summary </div>
<Div Class =" Display-field " >
@ Html. displayfor (model => model. Summary)
</Div>
<Div Class = " Display-label " >
Author </div>
<Div Class = " Display-field " >
@ Html. displayfor (model => model. Author)
</Div>
<Div Class = " Display-label " >
Thumbnail </div>
<Div Class = " Display-field " >
@ Html. displayfor (model => model. thumbnail)
</Div>
<Div Class = " Display-label " >
Price </div>
<Div Class = " Display-field " >
@ Html. displayfor (model => model. Price)
</Div>
<Div Class = " Display-label " >
Published </div>
<Div Class = " Display-field " >
@ Html. displayfor (model => model. published)
</Div>
</Fieldset>
<Fieldset>
<Legend> comments </legend>
<Div id = " Comments " >
@ {Html. renderaction ( " Index " , " Bookcomments " , New {Bookid = model. ID });}
</Div>
</Fieldset>
<P>
@ Html. actionlink ( " Edit " , " Edit " , New {Id = model. ID}) |
@ Html. actionlink ( " Back to list " , " Index " )
</P>

In the above Code, a new <fieldset> is added, which contains a <div>. the ID of the DIV is "Comments", and the DIV contains an HTML. renderaction (), which can be passed to the index action of the bookcomment controller by passing a bookid parameter.

Next, we need to update bookcomments/index view. In the example below,Create newLink is updated to display the form with Ajax instead of redirection. Some links will also be removed, because we only need to add capabilities and do not need to manage these comments. The Code is as follows:

@ Model ienumerable <mvcapplication. Models. bookcomment>
@{
Viewbag. Title = " Index " ;
}
<H2>
Index </H2>
<P>
@ Ajax. actionlink ( " Create new " , " Create " , New
{
Bookid = viewbag. bookid
},
New Ajaxoptions {updatetargetid = " Addcomment " })
</P>
<Div id = " Addcomment " >
</Div>
<Table>
<Tr>
<TH>
Comment
</Th>
<TH>
Created
</Th>
</Tr>
@ Foreach ( VaR Item In Model)
{
<Tr>
<TD>
@ Html. displayfor (modelitem => item. Comment)
</TD>
<TD>
@ Html. displayfor (modelitem => item. Created)
</TD>
<TD>
@ Html. displayfor (modelitem => item. Book. Title)
</TD>
</Tr>
}
</Table>

Note that the automatically generated bookcomments/create view must be changed. Use Ajax. beginform to replace the default html. beginform. Another thing is to tell the form to call a javascript: function reloadcomments () When Ajax is submitted (). This function uses jquery's Ajax request to retrieve the updated comment list. Create a hidden field with the bookid to replace the automatically created drop-down list.

The Code is as follows:

@ Model mvcapplication. Models. bookcomment
@{
Viewbag. Title = " Create " ;
}
<H2>
Create </H2>
<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>
<SCRIPT type = " Text/JavaScript " >
Function reloadcomments (){
$ ( " # Comments " ). Load ( " @ URL. Content ( " ~ /Bookcomments/index? Bookid = " + Viewbag. bookid) " );
}
</SCRIPT>
@ Using (Ajax. beginform ( New Ajaxoptions
{
Oncomplete = " Reloadcomments () "
}))
{
@ Html. Hidden ( " Bookid " ,( Int ) Viewbag. bookid );
@ Html. validationsummary ( True )
<Fieldset>
<Legend> bookcomment </legend>
<Div Class = " Editor-label " >
@ Html. labelfor (model => model. Comment)
</Div>
<Div Class = " Editor-field " >
@ Html. editorfor (model => model. Comment)
@ Html. validationmessagefor (model => model. Comment)
</Div>
<P>
<Input type = " Submit " Value = " Create " />
</P>
</Fieldset>
}

To complete this example, we also need to update some code in bookcommentscontroller:

(TRANSLATOR: Why does the author always say the last step? How many are the last steps? Don't worry. It will be done right away)

 

 Using System;
Using System. Collections. Generic;
Using System. Data;
Using System. Data. entity;
Using System. LINQ;
Using System. Web;
Using System. Web. MVC;
Using Mvcapplication. models;

Namespace Mvcapplication. Controllers
{
Public Class Bookcommentscontroller: Controller
{
Private Bookdbcontext DB = New Bookdbcontext ();
//
// Get:/bookcomments/
Public Actionresult index ( Int Bookid)
{
Viewbag. bookid = bookid;
VaR Bookcomments = dB. bookcomments. Include (
B => B. Book). Where (B => B. bookid = bookid );
Return Partialview (bookcomments. tolist ());
}
//
// Get:/bookcomments/create
Public Actionresult create ( Int Bookid)
{
Viewbag. bookid = bookid;
Return Partialview ();
}
//
// Post:/bookcomments/create
[Httppost]
Public Actionresult create (bookcomment)
{
If (Modelstate. isvalid)
{
Bookcomment. Created = datetime. now;
DB. bookcomments. Add (bookcomment );
DB. savechanges ();
}
Viewbag. bookid = bookcomment. bookid;
Return Partialview (bookcomment );
}
Protected Override Void Dispose ( Bool Disposing)
{
DB. Dispose ();
Base . Dispose (disposing );
}
}
}

In the preceding example, the index action has been updated and the bookid parameter of the integer is accepted. This is set to viewbag. Another important change is to return a partial view instead of returning the complete view (blocking the full layout display ). If you still remember the previous example, we re-use the same view to execute Ajax requests and check in the view to see if it is an Ajax request to disable layout. Because this view is displayed only through Ajax, it is simple to update the Controller to return a partial view.
Finally, the create action is updated. The basic create action receives a bookid like the index action and returns a partial view. Second, the create letter action has been updated to set the comment creation date. If an error occurs, a partial view is returned. Edit, details, and delete actions have been removed because they are useless. These views can also be deleted because they are not used.
Now, when users browse the details of a book, they can see all the comments
If they want to add their own comments, they can see the list of comments that have been posted. If they want to add their own content, they can click Create new link, enter their content, submit, and automatically view the content they just submitted without leaving the book details page.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.