0

Well I have a backbone.js model here

define ['jquery','underscore','backbone'] , ($,_,Backbone) ->
class Student extends Backbone.Model
    idAttribute : "UserKey"

    urlRoot : "Api/Student"

    defaults: 
        UserKey: null
        FirstName : ""
        LastName : ""
        Username : ""
        Password : ""
        Age : 18 

    initialize : ->
        #console.log "You have been initialized"

And Lets see I have a controller here : -

 public class HomeController : Controller
{        

    private Repository<Student, PortalContext> repo;
    public HomeController()
    {
        repo = new Repository<Student, PortalContext>(new PortalContext());
    }

    [HttpGet]
    public ActionResult All()
    {
        IList<Student> studs = repo.GetAll().ToList<Student>();
        return this.Json(new { Students=studs }, JsonRequestBehavior.AllowGet);
    }
    [HttpGet]
    public JsonResult Get(int id)
    {
        Student student  =  repo.FindBy(x => x.UserKey ==id).Select(x=>x).SingleOrDefault<Student>();
        return this.Json(student,JsonRequestBehavior.AllowGet);
    }

    [HttpPut, ActionName("Student")]
    public ActionResult Update(Student student)
    {
        repo.Edit(student);
        repo.Save();
        return Json(student);
    }
}

And here is my View.Coffee file where I am saving the Model :

define ['jquery'
    ,'underscore'
    ,'backbone'
    ,'text!/Templates/Student/View.htm'] , ($ , _ , Backbone , ViewTemplate) ->

class StdView extends Backbone.View

    _.templateSettings = { interpolate: /\{\{(.+?)\}\}/g };

    template : _.template(ViewTemplate)

    events : ->
        "click #back":"Back"
        "click #save" : "Save"

    Save : ->
        console.log "tryng to save"
        @model.save
            'FirstName' : @$el.find("#txtFirstName").val()
            'LastName' : @$el.find("#txtLastName").val()
            'Age': @$el.find("#txtAge").val()

        ,
            wait:true
            success: =>
                alert "Saved"
        @


    Back: (e)->
        window.history.back()
        false

    initialize : (options) ->       
        @render()

    render :->
        #console.log "this is details"
        @setElement @template @model.toJSON()
        @

It sometime saves the model but sometimes it posts back to the server i.e the backbone doesnt save the data rather it attaches the data into browser url like this

http://abc.com/?firstname=Joy&lastname=Roy&age=19#browse/1

and posts back . But sometimes it saves the data and shows the alert . I am not sure why this is happening Can someone put some light why it is happening like that? ?

Joy
  • 6,438
  • 8
  • 44
  • 75
  • Where is your [HttpPost] method in your controller? I would certainly consider using MVC Web Api. Much cleaner and integrates seamlessly with Backbone. Remember [HttpPut] is for "Changing"/"Updating" a student and [HttpPost] is for "Creating" a new student. So Backbone will call the POST when the student does not exist in your collection and [HttpPut] when updating a student in your collection. – TYRONEMICHAEL Sep 15 '12 at 17:16
  • @TyroneMichael Well I am currently having problem with [HttpPut] only . So you mean to say the Item doesnt exist ? But I am rendering from an existing model which exists in the collection only ? – Joy Sep 15 '12 at 17:54
  • So are you taking a model inside a collection then modifying the values? I cant see it in your code, but how are you getting your collection initially? – TYRONEMICHAEL Sep 15 '12 at 19:19
  • @TyroneMichael well I am rendering a model from collection through fetch method and populating into a view (backbone view ) . Now i have a save button and the template consists of inputs which are bound to model attributes . Now template renders with the model fetched from colleciton and on pressing save the model should actually update ( which i have written in controller using HttpPut. But what happens is tht if its the first time then the server post back is happening .After two times pressing that.The alert for success fires.However if i change any value of inputs.The same error comes back – Joy Sep 15 '12 at 21:02
  • @TyroneMichael I got the solution . I had to add false at end of event then it doesnt posts the entire page to server. But I always thought backbone included that by default ? Doesn't it do that already ? what if I need to return the object itself from here ? In that case it would get posted again isnt it ? how to overcome that ? – Joy Sep 16 '12 at 04:17
  • If your save button is a submit button inside a form, you have to include return false or preventDefault() otherwise the form will still submit to the url included in your form. Backbone wont presume, nor should it, that you are trying to submit the form through Backbone and not with the form itself. I am guessing you still want the form to submit if js is disabled? I am not sure what you mean by returning the object again. Your should model still should be in memory. Why would it post again? Backbone presumes the Model has changed when calling save. – TYRONEMICHAEL Sep 16 '12 at 05:43

1 Answers1

0

After our discussion, Nettuts just provided a great 20 min video tutorial on what I believe will help you better than I can. Take a look and let me know if you have any more questions. He is using Laravel for his server, but from what I can gather, your problem is not with your sever but rather with your client application. Here is the video.

TYRONEMICHAEL
  • 4,174
  • 4
  • 30
  • 47