Showing posts with label mvc4. Show all posts
Showing posts with label mvc4. Show all posts

Wednesday, January 2, 2013

Example to use ajax post in MVC 4

Since MVC4, it is recommended using jquery and unobtrusive javascript to post form. Here is a quick example to do it in a view to use $.ajax and $.post

   1:   
   2:  <h3>Form 1:</h3>
   3:  @using (Html.BeginForm("Login", "Account", FormMethod.Post, new { Id="form1"}))
   4:  {
   5:      <input type="text" id="text1" name="text1" /><br />
   6:      <input type="text" id="text2" name="text2" /><br />
   7:      <input type="submit" value="submit" id="form1submit" />
   8:  }
   9:   
  10:  <h3>Form 2:</h3>
  11:  @using (Html.BeginForm("About", "Home", FormMethod.Post, new { Id = "form2" }))
  12:  {
  13:      <input type="text" id="txtName" name="txtName" value="abc" /><br />
  14:      <input type="submit" value="submit" id="form2submit" />
  15:  }
  16:   
  17:  @section scripts{
  18:      <script type="text/javascript">
  19:          $(function () {
  20:              $('#form1submit').click(function () {
  21:                  $.ajax({
  22:                      url: '/Home/About',
  23:                      type: 'POST',
  24:                      data: $('#form1').serialize(),
  25:                      success: function (data) {
  26:                          alert(data);
  27:                      }
  28:                  });
  29:   
  30:                  return false;
  31:              });
  32:   
  33:              $('#form2submit').click(function () {
  34:                  var action = $('#form2').attr('action');                
  35:                  $.post(action, $('#form2').serialize(), function (data) { alert(data); });
  36:                  return false;
  37:              });
  38:   
  39:          });
  40:          
  41:      </script>
  42:  }

Tuesday, January 1, 2013

Entity Framework One-to-One Relationship Association

In this scenario, Author has many books (1 to m). And the Author has the latest Book (1:1) as well.

Using the link as a reference, here is how I come up with the model and association.

Model:

public class Author
    {
        public int AuthorId { get; set; }
        public string Name { get; set; }
        public int LatestBookId { get; set; }
        public Book LatestBook { get; set; }
        public List<Book> Books { get; set; }
    }
    public class Book
    {
        public int BookId { get; set; }
        public string BookName { get; set; }
        public int AuthorId { get; set; }
        public Author Author { get; set; }
    }

DbContext to set up the relationship using Fluent API

    public class EntityMappingContext : DbContext
    {
        public DbSet<Author> Authors { get; set; }
        public DbSet<Book> Books { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Author>()
                        .HasRequired(a => a.LatestBook)
                        .WithMany()
                        .HasForeignKey(u => u.LatestBookId);
            modelBuilder.Entity<Book>()
                        .HasRequired(a => a.Author)
                        .WithMany()
                        .HasForeignKey(u => u.AuthorId).WillCascadeOnDelete(false);
        }
    }




Wednesday, December 26, 2012

How to use MVC templates and knockout

Recently I am wirting a MVC4 application with some CRUD operation.
MVC provide the templates view to make model view easier. Knockout is a good javascript library to provide the view model binding. Then how to use best of the two together?

Here is a link which shows a good example to use both.

Basically, the template view only needs to add the attribute data-bind with the model property name.
and the property name can get from ViewData.ModelMetaData.PropertyName.

The link above only shows how to add the data-binding to the template. There are still a few things to be done to use knockout.

Knockout needs a ViewModel javascript to track the items and the code sample only returns a C# Model object.

Here is the data transform maps needed.
C# <Object > ---> JSON (javascript object) ---> KnockOut ViewModel

1. To translate model to json, use the following code,
@Html.Raw(
Json.Encode(ViewData.Model));

However, Json class is from a System.Web.Helpers assembly, which not included by MVC4.
The assembly needs to be added to the project from GAC.

2. knockout mapping is a js library to convert javascript object to viewModel,
which can be downloaded from here..

ViewModel = ko.mapping.fromJS( jsonObj );

Wednesday, December 19, 2012

Create the right connection name for Entity Framework Code First

When setting up the connection string for the Entity framework code first as default to use, the connection name should be the FULL namespace to the context.

For Eg.
<add name="EFWebTest.Models.BlogContext" providerName="System.Data.SqlClient" connectionString="Data Source=.;Integrated Security=SSPI;Initial Catlog=aspnet-EFWebTest" />

The connection string is using sql server. So when the context is loaded, the default database structure will be created in sql server.

Another option is to pass the connection string name in the dbcontext constructor such as,
public sampleDbContext : base("DefaultConnection") {}

Thursday, December 6, 2012

Include twitter bootstrap scripts in MVC 4

Recently I have been looking at the Twitter bootstrap, this is so far the best design toolkit to start your web site. There is a tutorial to start to learn it.

Also now there is a bootstrap package for asp.net mvc4 to install from Nuget.

If you want to use it directly in the MVC4 layout by adding the bootstrap minify script in the layout view page, you will have the error in browser such as,

Unhandled exception at line 6, column 27 in http://localhost:63410/Bootstrap/js/bootstrap.min.js
0x800a138f - JavaScript runtime error: Object expected

To fix this, you need to include JQuery (1.7 above) first before add the bootstrap.min.js
   
@Scripts.Render("~/bundles/jquery")
<script src="/Bootstrap/js/bootstrap.min.js" type="text/javascript"></script>



Saturday, November 17, 2012

MVC4 Web API Starter needs to know

I have just tried to use the MVC 4 Web API. There are some findings that needs to know during the process,

1. Use cUrl command line tool to test out the rest end points

2. Modify the IIS or IIS Express settings to enable verb PUT, DELETE
This is a link to show how to do this.

3. If need to use web API provided HttpClient class
In package manager console, run:
    Install-Package Microsoft.AspNet.WebApi.Client projectname
to install the necessary libraries


4. This will be a quick example to return the result.

By Calling add MediaTypeWithQualityHeaderValue("application/xml"), a xml format data will be returned. By default, web api return Json format data.

use new System.Net.Http.HttpClient() to send Form data
To use xml format data, need to add the MediaTypeHeader
clt.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
To get the result
 var result = clt.GetAsync(new Uri("http://localhost:52094/api/videos")).Result
 
For post complex type data, Call PostAsJsonAsync() such as
clt.PostAsJsonAsync("http://localhost:52094/api/videos/222", customer).Result
 

5. There are some old examples to use HttpRequestMessage and its extension method CreateContent, which are deprecated. it is much easier now.

6. In debug->immediate window, enter GlobalConfiguration object to check the current formatters.
GlobalConfiguration.Configuration.Formatters

Count = 4

[0]: {System.Net.Http.Formatting.JsonMediaTypeFormatter}

[1]: {System.Net.Http.Formatting.XmlMediaTypeFormatter}

[2]: {System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter}

[3]: {System.Web.Http.ModelBinding.JQueryMvcFormUrlEncodedFormatter}
 
 


 

Monday, November 12, 2012

Create asp.net MVC 4 supported membership database

In traditional asp.net, you can run aspnet_regsql to create the membership database.

In this one I will explain how to create mvc 4 membership database.

1. In web.config, add the default (localdb) connection

    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=dbname;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\dbname.mdf" />

2. Install the necessary packages reference in NuGet
Install-Package DotNetOpenAuth
Install-Package DotNetOpenAuth.aspnet
Install-Package Microsoft.AspNet.WebPages.OAuth
Install-Package WebGrease
Install-Package WebMatrix.Data
Install-Package WebMatrix.WebData
Add reference to system.web.helpers from nuget packages, make sure copy to local is true

3. Include the codes from an internet application sample
\Models\AccountModels.cs
\Filters\InitializeSimpleMembershipAttribute.cs
\Controller\AccountController.cs
\Views\Shared\_LoginPartial.cshtml
\Views\Account\* (update the namespace)

4. Also in web.config, remove the default membership provider and role provider section.

5. To use OAuth with Facebook, Google, Twitter etc,
Need to include the file \App_Start\AuthConfig.cs to uncomment the provider code with their appid and app seceret.
Also modify the global.asax.cs to add the line of the code,
AuthConfig.RegisterAuth();

Thursday, September 6, 2012

Update: signalR-0.5.3 and mvc4 worked

I want to try out the signalR library in mvc 4, so pretty much I follow the basic tutorial to have the basic "chat" program. First,  I run Install-Package "signalR" to install the packages in to the project.
After quickly get the codes there, and hit F5. Oops, it doesn't work. Then here is long hours google and try but I just have no luck. Browsing to "/signalr/hubs" just always gives me the 404 error.

Just an experiment, I recreated a mvc 3 project and running the same codes. This time, browse to "/signalr/hubs" actually returns me the proxy javascript. But I still have javascript error when I tried to send the message (strat to chat). However, If I use an old version (0.3.4), it all WORKS prefectly. The version I get from the msdn sample in here.

Update: Just saw on 11 Sep, there is a new update from Nuget. So I installed it to my MVC4 project.
But specifically in the package manage console, I am running,
install-package signalR -version 0.5.3 <projectname>

Then it all worked. only still in the _layout file,
I am using
<script src="@url.Content("~/scripts/jquery.signalr-0.5.3.min.js") type="text/javascript"></script>
rather than
mvc4 bundle javascript, @Scripts.Render(...)

Next, we can explore how to use signalR within BizTalk to be able to update the client the service/task progress.




Tuesday, September 4, 2012

Jquery file upload in ajax

Recently need to upload pictures to server side, and it should be in ajax way with a progress bar.
The default $.ajax doesn't support form data posted. So here is the jQuery Form Plugin to rescue.
And there is a blog example to use it within asp.net mvc.
Update: just find another blog with links to 7 javascript ajax upload library

Wednesday, August 29, 2012

asp.net MVC4 - $.getJSON with controller and knockout

In this scenario, I am trying to call a backend controller to load the data from backend.
Then the data will be returned as a JSON data to web and mapping back to a knockout view model for binding. And the knockout binding section should be shown by jquery ui dialog and update back to controller for saving.

Here are the listed issues that I got,

- In controller, return Json(data, JsonRequestBehavior.AllowGet), or else $.getJSON call back function won't be triggered if you use get.

- In controller, use new JavaScriptSerializer().Seralize(Model) to return a JSON string representation of data. The string will be used for knockout to load to viewModel

- knockout mapping is a plug-in for automatically mapping the data from JSON to view model. it can be downloaded here.

- Use the following code to create the viewmodel and applybinding
var koModel = ko.mapping.fromJSON(data);
ko.applyBindings(koModel);


Tuesday, August 28, 2012

asp.net mvc 4 - webgrid add it as reference and use javascript in it

1. To use @Html.WebGrid in the razor view page by default it won't be loaded.
The webgrid is in System.Web.Helper, and it needs to be added in web.config like below in system.web section,

< compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>


2. By default, you can use format: (item) => item.GetSelectLink()) to add a select link for each row.

However, I want to add a javascript function to pass an itemId, then open a jquery ui dialog to load the values and save it by Json format.

You can use HtmlString to override it, format: (item) => new HtmlString("<a href=# onclick=...")

A cleaner way will be create a htmlHelperExtension to return the html string, such as,

    public static class HtmlExtension
    {
        public static IHtmlString Link(this HtmlHelper htmlHelper, Post item)
        {
            var anchor = new TagBuilder("a");
            anchor.AddCssClass("sel");
            anchor.Attributes["src"] = "#";
            anchor.Attributes["onclick"] = string.Format("select({0});", item.Id);
            anchor.SetInnerText("select");
            return new HtmlString(anchor.ToString());
        }
    }

Then in the razor view page, it will become format:(item) => Html.Link((Post)item.Value)
The namespace for the HtmlExtension should be declared, and remember to pass item.Value.

Sunday, August 19, 2012

A very clean article to discuss when to use RenderAction or RenderPartial in MVC3

This post is the best one so far to explain when to use RenderAction and when to use RenderPartial.

RenderAction basically can be a good place holder for some static contents that can be defined in _layout page. However, if the content is driven by main view content, it will be better define it in section area. There is a good tutorial by ScottGu.
Also in the view if you want to get the current action and controller, you can get it from ViewContext.RouteData.Values["controller" or "action"]