Category Archives: MVC

JQuery Auto complete work with bakcode by using asp.net mvc

Recently to convert the new website, I have a bookinng form for the clients to finished the booking,there is some exiting data need to using auto complete. In the past I alway use ajax tool control kits to achieve that result. But now I am kind of fun for JQuery. Here is the Jquery Autocomplete textbox

First I have databses contain all the subuerbs, here is my database table.

databaseSuburbs

here is my action in my BookController:

databseJasonResult

I let it return json because json is the fast and easy analyse data at moment.

Then in your view , just add the reference to JQuery UI:

autocompleteJqury

You could ignore the timepicker.min.css, and timepicker.min.js, I use it to picker up the time, for autocomplete don’t need those two references.

here just in you view you just need one more line.

@Html.TextBox(“SearhToSuburb”, null, new {type=”text”,@class=”form-control”, @id = “search_to_suburb” })

That’s it. Simply isn’t it. Have fun. Below is what will it looking like.feels

Advertisements

Using two Way Adding “active” tag to your navigation list in an asp.net mvc Layout page

Recently my task need convert this website http://www.royalecoach.com.au/royale.asp (this is wrote by using classic asp) into asp.net MVC.

First I need to create a layout.cshtml for my the new version of this website.Then navigation need add a class named active to it when the action method has been called.

The first way is very simpley, you could wirte a logic to your view, here is one solution:

addClassNametoLi

But the rule of MVC is the view must be simply as possible, I don’t like this nasty and yuck c# code sit in there. So there is a way just by write a CustomHtmlHelpers to improve it.

here is my class file:

htmlHelper

 

Then in your layout page ,your could use it like:

layoutMenu

That’s it. By the way, I am using asp mvc4. Hope that could help some one else.

Have fun:)

Basic struction — create Database first ASP MVC Application(Models in three way)

Here in the internet have a lot tutorial introduction about create code first asp mvc application, but in the real life world the database always aready is exsiting. I am not mvc experter, I am fresher now. It took me a while to get the basic struction a while.So I like to write it down wish this could help some people like me struggling in the beginning.

OK, let me asume that we are going to create a online store ecormmerce website.

Way one: basic struction

Then you create a new MVC project through VS2013, first thing is add a connection string to your root web.config file.

It is like this:connectionStr

Modelsisnothingjustclassfile

Models is nothing just class file. You map your table to class file, then when you create a controller you could select strongly type.

finally is the Add one line to Global.asax to stop populater some seed data

GlobalNeedAddOneLine

See the null meaning don’t popular seed data.

Way two: basic struction(Models is another project)

I won’t talk about the controller or the views. But Models could anything, Web services, WCF and don’t sit in your project, the model is not neccessary sit in your project.So your project only have controller and Views, but the Models is independent. Here is a simple practise I did in my Demo struction is like this:

separateModelMvc

Way three: basic struction(Model is your entity Framework)

MvcEntityFrameworkStruction

How to create Picture Upload by using ASP MVC 4

This is a very simply example for how to using asp MVC. In this example doesn’t involved with your database. So start from create a model here is your code for your picture upload model. model is cs file, so save below code as PictureModel.cs


using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace MvcDemo.Models
{
    public class PictureModel
    {
        [Required]
        public HttpPostedFileBase PictureFile { get; set; }
    }
}

Then create a action event to your Controller. Controller also just cs file, so save below to one of the Controllers file


//by default, this will be called by get 
public ActionResult PictureUpload()
        {
            return View();
        }

here is the view file code. view is the PictureUpload.cshtml


@model MvcDemo.Models.PictureModel
@{
    ViewBag.Title = "Picture Upload";
}


Picture Upload

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = “multipart/form-data” })) { @Html.AntiForgeryToken() @Html.ValidationSummary(true)

PictureModel 

@Html.LabelFor(model => model.PictureFile)

 

@Html.TextBoxFor(model => model.PictureFile, new { type = “file” }) @Html.ValidationMessageFor(model => model.PictureFile)

} @section Scripts { @Scripts.Render(“~/bundles/jqueryval”) }

After submit, it will call the post, below is the action event for post


[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult PictureUpload(PictureModel model)
        {
            if (model.PictureFile.ContentLength > 0)
            {
                var fileName = Path.GetFileName(model.PictureFile.FileName);
                var filePath = Server.MapPath("~/Content/Uploads");
                string savedFileName = Path.Combine(filePath, fileName);
                model.PictureFile.SaveAs(savedFileName);                
            }
            return View(model);
        }

Revision:how to use backbone

three way to create your  model:

Person = Backbone.Model.extend({})
Person = Backbone.Model.extend({
defaults:{
name:"";//Model arrow undefined data
create:new Date() //here arrow put PHP function
}
});
Person = Backbone.Model.extend({
defaults:function(){
return   {  name:"";  //Model arrow undefined data
create:new Date()
}
}
});

Read and Write:

var person = new Person({ name:”Sandy”,age:”12″});

person.get(“name”);//” Sandy”

person.set({name:”Anna”,age:”12″});//overwrite it

Create Simple View

PersonView = Backbone.View.extend({

render:function(){

var person = “<p>” + this.model.get(“user”) + “</p>”;

$(this.el).html(person);

}

});

“this.el” meaning: every View Model create a Page Scope, el means the root tag<div></div>,

Get Model data Add into HTML page

var personView = new PersonView({

model:person;

})

personView.render();

console.log(personView.el);//check the el

Get Data from the server(RESTful way)

var Person = Backbone.Model.extend({urlRoot:”/person”}); //point to the data sourse

var person = new Person({id:1}); //point to your object

person.fetch();//get /person/1

person.save();//put /person/1

var newPerson=new PersonModel(); //create a new object

newPerson.set({name:”Sandy Zhang”}); // give the an name

newPerson.save(); // insert into /person

newPerson.get(“id”); //2

newPerson.destroy();// Delete /person/2

Create Better View

var PersonView = Backbone.View.extend({

tagName:”article”,

id:”personOne”;

class:”person”,

attributes:{title:this.model.get(“name”)},

render:function(){

var person=”<p>” + this.model.get(“name”)+”</p>”;

$(this.el).html(person);

}

});

this will render html sourse:

<article id=”personOne” class = “person” title=”Sandy Zhang”>

<p>Sandy Zhang</p>

</article>

Cache of the jQuery object

$(“#personOne”).html();

in Backbone.js: $(this.el).html(); or better way : this.$el.html()

el  is  generated for the cache of jQuery object, so that it can be used repeatedly without fear of generating multiple instances of the jQuery object.

Built-in template engine(underscore template)

use render() seems not elegant ,now we use underscore template

var PersonView = Backbone.View.extend({

tagName:”article”,

id:”personOne”;

class:”person”,

attributes:{title:this.model.get(“name”)},

template: _.template(‘<p><%= name %></p>’),

render:function(){

data = this.model.toJSON();

$(this.el).html(template(data));

}

}); // Cool! looking better

Track your instance

var person = new Person({name:”sandy”}); //create a instance

person.on(“change”,function(){

alert(“Something changed on ” + this.get(“name”) );

});

person.on(“change:age”,function(){

alert(this.get(“name”) +”,Your age has been changed ”  );

});

Change data to JSON format

var person = new Person({id:1});

console.log(person.toJSON());

//or

console.log(JSON.stringify(person));

Now Add View event

var PersonView = Backbone.View.extend({

tagName:”article”,

id:”personOne”;

class:”person”,

attributes:{title:this.model.get(“name”)},

template: _.template(‘<p><%= name %></p>’),

render:function(){

data = this.model.toJSON();

this.$el.html(template(data));

},

events:{ “mouseover” :”showMore”,},

showMore:function(){…….},

});

Advance Level

1.Server <= (get) model (data) => view (rendering) => DOM

var PersonView = Backbone.View.extend({

input:_.template(‘<input type=”text”><%= name%></input>’),

submit: _.template(‘<button type=”submit”>Change Name</button>’),

render: function(){

data = this.model.toJSON();

this.$el.html(input(data)).html(submit);

}

});

Now we can  change name now, the question is how do you know the model data has changed? This needs to view it through the event.

var PersonView = Backbone.View.extend({

events:{“submit button”:”updateName”}

updataName:function(){

newName = $(this).val();  // this=button!

if(newName !== this.model.get(‘name’)){

this.model.set({name:newName}); }

else{ return;}

}

});

Well…it did work, but the problem is : should belong Model processing logic  put in the View now. So we reconstruct it.

var PersonView = Backbone.View.extend({

events:{“submit button”:”updateName”}

updateName:function(){

newName = $(this).val();

this.model.updateName(newName);

}

});

var Person = Backbone.Model.extend({

updateName: function(newName){

this.set({name:newName});

this.save(); // tell server to save the new name into database

}

})

2.The above, we pass the parameter value changes transferred to the Model, and then further processed by the Model it wants to do.

Now, the loop model like this:

Server <= (updated) model (proceed) <= (notification) view <= (user interaction) DOM

If the data model changes, how to notice the view? You might immediately think of the render method can be performed immediately after the completion notification view:

var PersonView = Backbone.View.extend({

updateName:function(){

newName = $(this).val();

this.model.updateName(newName);

this.render();

}

});

Ah good idea …… but it is not always useful, because the value of the model could be changed elsewhere, such as in another view . So, how to notify the specified view  response to the model changes?

So, use listenTo() function

var PersonView = Backbone.View.extend({

initialize:function(){

this.listenTo(this.model,”change”,this.render);

//this.model.on(“change”,this.render,this);

}

});

3. collection

a)Collect multiple model data

When there was more and more instances , in order to facilitate the processing of them, we usually think of them together with the array. Backbone.js Collection module provides a simplified way to help us:

var Person = Backbone.Collection.extend({ model:person });

var person.add{[{name:”Sandy Zhang”, id:1},{name:”Anna li”,id:2}]};

person.length //=>2

person.get(2) // => { name : “Anna li”,id:2}

person.at(0) //=>{ name:”Sandy Zhang”, id:1}

HTML5 Push State API

Backbone.history.start({pushState: true});

var App = new (Backbone.Router.extend({
initialize: function() {
this.person = new person();
this.personView = new personView({collection: this.person});
$(“#app”).append(this.personView.el);
},

index: function() {
this.person.fetch();
},

start: function() {
Backbone.history.start({pushState: true});
}
}));

$(function() { App.start(); });

Backbone Collection

run the code in the browse should look like

backbone3

here is the code for get the collection:

<script type=”text/javascript”>
Student = Backbone.Model.extend({
defaults:{
name:””,
age:””
}

});
ClassRoom = Backbone.Collection.extend({
model:Student
});

var student1 = new Student({name:”Sandy”,age:”20″});
var student2 = new Student({name:”Rachel”,age:”18″});
var student3 = new Student({name:”Anna”,age:”23″});
var collection = new ClassRoom([student1,student2,student3]);

</script>

Backbone – Router

On this post create 2 template,and use backbone router to communicate with those 2 pages, here is the code.

<script type=”text/template” id=”first_template”>
<label>My First View:</label>
<a href=”#second”>Go to Second View</a>

</script>

<script type=”text/template” id=”second_template”>
<label>My Second View:</label>
<a href=”#first”>Go to First View</a>

</script>

<div id = “container”></div>

<script type=”text/javascript”>
FirstView = Backbone.View.extend({
el:$(‘#container’),
initialize:function(){
this.render();
},

render:function(){
var template = _.template($(‘#first_template’).html(),{});

this.$el.html(template);

}

});

SecondView = Backbone.View.extend({
el:$(‘#container’),
initialize:function(){
this.render();
},

render:function(){
var template = _.template($(‘#second_template’).html(),{});

this.$el.html(template);

}

});

MyRouter = Backbone.Router.extend({
routes:{
“”:”firstPage”,
“first”:”firstPage”,
“second”:”secondPage”
},

firstPage:function(){
new FirstView();
},
secondPage:function(){
new SecondView();
}

});

var router = new MyRouter();
Backbone.history.start();

</script>

 

Backbone setup your Model

This could put on external file or you could put in the body area, test in browser, you should see things like this

backbone1

<script type=”text/javascript”>
           //create a new model named person, if you work with PHP framework like zend framework just use the model name you create in your php files
Person = Backbone.Model.extend({
initialize: function(){
console.log(“Object is created”);

//this is for track the value weather it changed or not
this.on(“change:name”,function(){
alert(“Name attribute value has been changed”);
});
this.on(“change:age”,function(){
alert(“Age attribute value has been changed”);
});
},
defaults:{
name:”Sandy”,
gender:”Female”,
age:”20″
},
//create a customer function
getPersonInfo:function(){
document.write(“<h2>Name is: ” +this.get(‘name’)+”,Gender is : “+this.get(‘gender’)+”,Age is:”+this.get(‘age’) +”</h2>”);
}
});
//create an object name sandy
var sandy = new Person();
document.write(sandy.get(‘name’)+”<br/>”);
document.write(sandy.get(‘gender’)+”<br/>”);
document.write(sandy.get(‘age’)+”<br/>”);
//create an object name simon and give different value to name,gender, age
var simon = new Person({name:”simon”,gender:”male”,age:”12″});
document.write(simon.get(‘name’)+”<br/>”);
document.write(simon.get(‘gender’)+”<br/>”);
document.write(simon.get(‘age’));
//call the customer function
sandy.getPersonInfo();
//this set function goes to overide the name then will have alert window
sandy.set({name:”SandyZhang”});
sandy.set({age:”30″});
</script>