Render Partial View from Javascript and pass model - javascript

I need to create partial views dynamically which require a model that is initially used. I can serialize the model and pass it to a javascript function but I can't figure out how to pass using jquery api load.
Here's what I'm currently doing.
var loader = $('<div class="loader"></div>');
loader.load(url);
$(cl).append(loader);
I call the partial like this in the cshtml page. This works fine.
#Html.RenderPartial("~/Views/Shared/_PartialView.cshtml", Model);
Also, calling load like this works works as well.
load('#Url.Action("_PartialViewAction", "Home")')
The issue is, I need to pass the model with it from a javascript/jquery call.
Update
So this was my mistake. It must be a Friday morning thing - this is actually very simple to accomplish. I only need to pass the serialized data to the controller and it loads the partial view.

You can save the object into a javascript var:
<script>
var viewModel = #Html.Raw(JsonNetConverter.Serialize(Model))
</script>
or like this :
var viewModel = { VariationID: #Model.id, ProductID: #Model.product, InStock: #Model.isStock, Price: #Model.price };
And leter take it:
load('#Url.Action("_PartialViewAction", "Home")', viewModel)

Related

Typeahead in ASP.net MVC

The first image shows that the method I created in user class.
The second image shows the controller that I created. How I take the data from GetGroupManagerAndFranchiseConsultantList? What should I need to write within view?
Right now you are returning Json. So I assume you are calling this call from something like this
<script>
$.getJSON("/Search",function(data){
// data is a JS OBJECT of your JSON data.
});
</script>
If you were looking to use MVC Views you need to return it as a view and use the built-in model binding.

Access property of an object of type [Model] in JQuery

So in my MVC project I have a custom Model called Survey, which contains a handful of properties. In the Survey Controller, I am saving Survey to a Session variable, so that the values of the survey's properties are persisted per session.
I want to be able to manipulate the DOM of a View based on the values of the session survey's properties. But I'm having trouble with how to access those.
I did find this relatively recent question that seems very similar but doesn't have an answer: Cannot access properties of model in javascript
Here's what I have so far: In the View I am getting the session's survey like so:
<input type="hidden" name="activeS" value="#HttpContext.Current.Session("Survey")" />
Then in the Section Scripts at the bottom I have this script to get that value and do something with it:
#Section Scripts
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
var survey = $("[name=activeS]").val();
$("[name=mddbccu][value=" + survey.mddbccu + "]").prop('checked', true);
})
</script>
End Section
If I insert "alert(survey);" after "var survey..." It does give me an alert that displays the type that the survey object is. So it looks like the survey is being retrieved fine. But if I try "alert(survey.mddbccu);" the alert simply says "undefined".
Note that the line after that ("$([name=mddbccu]...") I know works - having previously set a variable to a specific value, using that the appropriate item is checked. But in attempting to get the value of this particular property of the survey, nothing is checked.
So how do I get the values of the survey's properties here? Thank you!
Your approach would work with some hackery and workarounds but it is not in the spirit of MVC. Here is how you could accomplish it in the MVC way. Basically you move all the heavy lifting (parsing the item from the session) 0 to the controller and store the results in a ViewModel. This keeps the logic out of the view and makes for much cleaner and easier to maintain code.
If you have a ViewModel:
public ActionResult Survey()
{
SurveyViewModel model = new SurveyViewModel();
Survey surveySession = HttpContext.Current.Session("Survey") as Survey; // youll have to do extra null checks and such here
// map other properties from the survey object retrieved from the session to your viewmodel here!
model.mddbccu = surveySession.mddbccu;
model.otherProperty = surveySession.otherProperty
return View(model);
}
If you are just using the Survey object as the model inside the view then its even simpler:
public ActionResult Survey()
{
Survey model = HttpContext.Current.Session("Survey") as Survey;
return View(model);
}
Then, MVC magically selects stuff for you depending on what you have set in the controller. If you are using #RadioButtonFor(m => m.mddbccu, "three") then the radio will be selected if the value "three" was put into the property mddbccu in the controller.

Rendering more than just model attributes in Parse JS API (backbone.js) view templates

So I'm trying to use a join table to display a list of data in my Parse app. The javascript API is similar enough to backbone.js that I'm assuming anyone who knows that could help me. I can't show my actual source code but I think I simple twitter-like "user follows user" scenario can answer my question. So assume I have a join table called "follows" that simply contains its own objectId, the id of each user in the relationship, and some meta-data about the relationship (needing metadata is why I'm using a join table, instead of Parse.Relation). I want to have a view that finds all of the users the current user follows and renders an instance of another view for each case. From what I have so far, that would looks something like this.
In the intialize of the top level view (let's call it AllFollowsView), I would have something like this.
var currentUser = Parse.User.current();
var followsQuery = new Parse.Query(Follows);
followsQuery.equalTo("userId", currentUser.id);
followsQuery.find({
success: function(followsResult){
for (var i = 0; i < followsResult.length; i++){
var view = new OneFollowView({model:followsResult[i]});
this.$("#followed-list").append(view.render().el);
}//for loop
},
error: function(error){
console.log("error finding plans query");
}
});
OneFollowsView is just a view that renders an showing data about the relationship and listens for changes on that particular relationship (mainly change or delete in my case). I understand that by passing in the corresponding model with
var view = new OneFollowView({model:followsResult[i]});
I can print out attributes of that model in the OneFollowsView template like this
<li>You are following a user with the id of <%= _.escape(followedUserId) %></li>
My problem is that this only gives me access to the information stored in the "follows" object. How would I pass in the corresponding user models (or any other models that I can query for the id of) into the template so I can access them in the html in the same way. I would like to be able to run queries in one of the views and then access those models in the html. I know I can add attributes to the object before declaring a new instance of the lower level class with that object as the model, but that doesn't help me because I don't want to save it with new attributes attached.
EDIT: My render function for the top level function is empty at the moment. It's initilize function contains this line to render the template. I guess this should probably be in the render function and then I would call render from initialize.
this.$el.html(_.template($("#all-follows-template").html()));
Here's the render for the lower (individual li) view
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
this.delegateEvents();
}
From my understanding this just renders the template to el while parsing the model to JSON and then returns to allow chained calls.
The problem here lies in you render method. When you call this.template in your render method. That method, this.template is a template function returned by calling the _.template function. When you call your this.template method, the properties of the object you pass in will be available as instance variables in your template.
In your case you're passing in the JSON of the object. So, the properties of the model become names of variables available in your template. If you want to expose additional variables to the template you have a couple options: 1) Add to the jsonified model's attributes. 2) Send in the model as a top level variable and any additional variables you may want.
// option 1
render: function() {
var templateArgs = _.extend(this.model.toJSON(), { additionalVar: 'new var' });
var content = this.template(templateArgs);
$(this.el).html(content);
this.delegateEvents();
return this;
}
// option 2
render: function() {
var templateArgs = {
followResult: this.model.toJSON(),
additionalVar: 'new var'
};
var content = this.template(templateArgs);
$(this.el).html(content);
return this;
this.delegateEvents();
}
Either option is reasonable. I would probably go with option 2. Which allows you in the template to say something like:
<li> <%= followResult.someProperty %> <%= additionalVar %> </li>
Hope that helps. :)

Get returned object from controller into the javascript

In my controller, I send an object list into the view (index.cshtml)
return View(AdsPrevModel);
in my index.cshtml:
<div id ="ele">
<ul>
<li> name1<input id="a1" type="checkbox"/></li>
</ul>
</div>
when the user clicks the checkbox, I use jquery to know if the user checked the box or not:
My javascript file:
$('#ele :checkbox').click(function () {
if ($(this).is(':checked')) {
alert($(this).attr('id'));
} else {
alert('unchecked');
}
});
How can I get my AdsPrevModel into my js file?
I know I can do something like this:
In my html, add:
<input type="hidden" id="AdsPrevModel" value="#Model.AdsPrevModel" />
and in the js:
var adsPrevModel = JSON.parse(document.getElementById('AdsPrevModel').value);
Is there another option without adding a hidden input in my html?
Maybe something like the following in the js file:
var adsPrevModel = JSON.parse(Model.AdsPrevModel));
The best practise is
do an ajax call to that controller and that controller should return json results
return JSON( model ) ;
In the code you've shared there's nothing emitting the model to the client, so there's currently no direct way for the JavaScript code to access it.
Since you're binding the view to the model, the view can include it in various ways. It could be a series of hidden fields for the members of the model (not the model in its entirety, unless it can be represented as a string in its entirety). Something like this:
#Html.HiddenFor(x => x.SomeField)
#Html.HiddenFor(x => x.AnotherField)
This would create two hidden inputs for two fields on the model. Depending on how complex the model is, this could get cumbersome.
You might also emit the model to the JavaScript code directly in a similar fashion:
var someField = #Model.SomeField;
var anotherField = #Model.AnotherField;
Again, if the model is complex, this gets cumbersome quickly. Even if you try to build an actual JavaScript object from it:
var theModel = {
someField : #Model.SomeField,
anotherField : #Model.AnotherField
};
(Note also that I've seen Visual Studio get very confused when you mix razor syntax and JavaScript like this. Not so much in 2012 anymore, but a lot in 2010.)
You might use something like the JavaScriptSerializer to add a property on the model for a serialized version of itself. I've never done this before, but it should work. Something like this on the model:
public string SerializedCopy
{
get
{
return new JavaScriptSerializer().Serialize(this);
}
}
It might take some tweaking to get it to work, though.
Finally, a particularly clean option which only requires another request to the server would be to have another action which just returns the JSON version of that model. Something like this:
public ActionResult SomeActionName()
{
// get the model somehow, then...
return Json(AdsPrevModel);
}
Your JavaScript code would then just need to call this action to get the JSON object representing the whole model:
var theModel = {};
$.get('#Url.Action("SomeActionName", "SomeController")', function (data) {
// maybe do some error checking here?
theModel = data;
});
Then if your actual view isn't actually binding anything to the model then the action which returns that view doesn't need to fetch the model and supply it to the view. The JavaScript code would get the model by calling this other action which returns JSON data instead of a view.

How do I serialize data from non-form elements and make it accessable from params[:model]

I have a Sinatra app which loads information from an external API and displays it on a page. This is done in Sinatra which gets the information and puts it a temporary model instance (which is NOT saved), so it is easier to access all its propertys in the view.
Now when the user clicks a link I want the model instance to be saved to the database, which I think only can be done via AJAX etc. because the last request already finished and none of the instances is still alive. I thought I needed to extract all the information of the corresponding HTML elements and make an AJAX-Post to another route.
My problem is now, I want to be able to create(and save) the model using #model = Model.create(params[:model]). It would be clear what to do using a form, but that is not an option because all the data is displayed within a table and each table row is one instance of the model.
How do I serialize the data from the table row in which the clicked link is, so I can use it as described above?
UPDATE
I am using MULTIPLE instances of the object class, each in one tablerow!
I am using DataMapper, only the temporary objects are not stored!
I dont want to clutter up my whole setup!
Did you consider ActiveResource? You can use ActiveResource to maintain object state. If your REST API follows convention it would be very easy to map resource.
Regarding second half sending back data to your controller, you could store in hidden variable(s) and on post it should be easy to construct back the object and persist it to database.
Something like
#model
class MyModel < ActiveResource::Base
# set configs here
end
# To fetch record from REST API in controller or whatever
MyModel.find(1)
#in controller on form submit or AJAX
post "/path" do
MyModel.new(params[:myModel])
end
Update
To maintain state of object without using hidden form
in javascript you can have something like
var myModel = #{myModel.to_json}; #Ruby interpolation in HAML it will depend on templating language
on certain action you can update the JSON object
and to post using AJAX
$.post("post/path", myModel);
More Update
In External JS
function my_js_function(obj) {
/* do something useful here like setting up object hash etc
*/
}
In Ruby Template
<script>
var myObj = #{myObj.json}
my_js_function(myObj);
</script>
I found a pretty easy solution. It was nothing more than getting all the required values from the DOM and putting them into an Array!
application.js:
$(".enable").click(function() {
var table_row = $(this).closest("tr");
var model_array = new Array;
var elements_with_information = jRow.find("[name]");
elements_with_information.each(function() {
// Doing some checking on which kind of element
// it actually is and then basically doing:
model_array.push($(this).text());
});
// Constructing nested array to use `params[:model]`
var data = { "model" : {
"property1": model_array[0],
"property2": model_array[1]
}};
// Now doing the AJAX request
$.ajax({
url: "/model/doshit",
type: "POST",
data: data
});
});

Categories