I have a nested model with some value I want to pass it's value to controller by ajax call, i can send data fields of main model but i can't send data of nested model which are declare in model.
/****Model Code ******/
public class xyzmodel()
{
public xyzmodel()
{
address = new Addresmodel();
}
public int Id{set; get;}
public string Name {set; get;}
}
public class Addresmodel()
{
public string Address{set; get;}
public string Number{set; get;}
}
Now i have a controller
/***** Controller Action *****/
public JsonResult SavePricingSet(xyzmodel model)
{
}
/ I am try to send value to this action method by javascript /
function Data()
{
Id: $('##Html.FieldIdFor(model => model.Id)').val(),
Name : $('##Html.FieldIdFor(model => model.Name)').val(),
/**** Above ID and Name Value i can send to controller and it's also receive ***/
Address.Number : $('##Html.FieldIdFor(model => model.Address.Number)').val(),
/*** I can Get this Address.Number Value ****/
}
my question is that how can i send this type of nested model fields value
please give hint or idea
Regards,
Ajisha
Your address field has lower case a, but you're using upper case.
#Html.FieldIdFor(model => model.address.Number)
Related
I have a class that has another class inside, but this class has some fields that i donĀ“t want to show when call this controller.
So, how can i hide ?
I tried to Include and do a Select with a new Class DTO, but not success.
For example:
public class Father
{
public string name {get;set}
public FamilyName familyName {get;set;}
}
public class FamilyName
{
public string name {get;set}
public string sex {get;set}
}
Controller
public IQueryable<Father> GetFathers()
{
return db.Fater;
}
When i call the context Father, i have a Json with name and sex. If i need to just show the field "name", how should I do ?
You are Exposing database entities to the client, The client
receives data that maps directly to your database tables, that's not
always a good idea
You can define a data transfer object (DTO). A DTO is an object that defines how the data will be sent over the network.
DTO Class
public class FatherDTO
{
public string name { get; set; }
}
Controller
public IQueryable<FatherDTO> GetFathers()
{
return new FatherDTO(){ name = db.Fater.name };
}
You can convert to DTOs manually in code. Another option is to use a library like AutoMapper that handles the conversion automatically.
For more details check this link
There are a couple of ways to do so.
1.Create an anon. type with the wanted properties.
// controller
public object GetFathers()
{
return db.Father.Select(f => new
{
name = f.name,
familyName = new { name = f.familyName.name }
});
}
2.Create a DTO or the same class with a new instance using select. In order to do that, you will need the query to execute since EF cannot translate new Father into sql.
// controller
public IEnumerable<Father> GetFathers()
{
return db.Father.ToList().Select(f => new Father
{
name = f.name,
familyName = new FamilyName { name = f.familyName.name }
});
}
Do stuff with the JSON serializer (custom attributes\custom converters etc.)
I've to pass a bool inside -> "#Html.ActionLink(" ", "Like", new { id = Model.Id #*, Pass bool value here *#}". My model doesn't contain a bool property nor can I add it(database first) or replace the model with a ViewModel. Is it still possible to pass a bool value to my method somehow?
My method Like signature takes a Guid Id and a bool in parameter.
Can I somehow pass bool:
#Html.ActionLink("Like!", "Like", new { id = Model.Id, #* true bool*#}
#Html.ActionLink("Disike!", "Like", new { id = Model.Id, #*false bool*#}
To:
public ActionResult Like(Guid id, bool getBool)
{
if (getBool == true){
return Content("Liked!");
}else if (getBool == false){
return Content("Disiked!");
}
Any idea how to pass a bool value from view to controller?
You pass a bool the same way you pass your model id:
#Html.ActionLink("Like!", "Like", new { id = Model.Id, getBool = true})
#Html.ActionLink("Disike!", "Like", new { id = Model.Id, getBool = false})
Ultimately there's nothing special about Model.Id. It's just a Guid. Values passed in don't have to come from anywhere in particular. Just pass in whatever.
There is not such thing "I can't replace the model with a ViewModel".
This is the idea of ViewModel, that is, to make a model that will be different from the database model and will fit to the view requirements.
e.g. If you have this model in your database:
public class Person
{
public int PersonID { get; set;}
public string Name { get; set;}
public string password { get; set;}
}
and you want to verify the password in the view you don't need to make in your model a propery that verify the password, this you do in the ViewModel class:
public class PersonVM :Person
{
public string verifyPassword { get; set;}
}
note, that not allways you'll inherit the origin model in the VM.
After creating the VM, you create a view that the model of that view is your VM that you created for the view. this way you can pass and get any additional information with your view.
I'm developping an application based on asp.NET MVC 5
This Application downloads a big deal of data from a local webservice and should display it.
Because it is much data, I call the webservice through a partial view, like this:
<div class="partialContents" id="partialContent" data-url="/Home/Action">
Loading...
</div>
This is loaded asynchronous with the following JS-Code:
$(document).ready(function (e) {
$(".partialContents").each(function (index, item) {
var url = $(item).data("url");
if (url && url.length > 0) {
$(item).load(url);
}
});
});
This works like intended.
But now I have to pass the values of a form to this partial view.
I know I can pass arguments as usual, like a request to /Home/Action/Params but I have to pass many arguments of which some might not be set or empty or null.
Because of this, I looked for a possibility to pass a object or a value of the ViewBag or something like this to the partial view.
Is there a possibility to pass a Model-Object to the Controller in my code?
The data has to go to the controller for further validation and so on. I know I can pass a model to the view itself, but I need those data in my controller.
My controller is accessed as following:
public ActionResult Index()
{
//Do things
return View(model);
}
public ActionResult Action()
{
//Validate the Form-Data
//Download Data from Webservice
return PartialView("MyPartialView", model);
}
Any help or tipps would be greatly appreciated.
Maybe I have to edit the Javascript-Code, but I don't usually code in JS, so I have the code from following source (followed his tutorial): blog.michaelckennedy.net
//Additional Info
My ViewModel looks like this:
public class PostForm
{
public string DatumVon { get; set; }
public string DatumBis { get; set; }
public string Werk { get; set; }
public string Pruefplatz { get; set; }
public string Auftrag { get; set; }
public string Gueltig { get; set; }
}
and my Java-Request like this:
$(item).load(url, {"DatumVon":dateVon, "DatumBis":dateBis, "Werk":werk, "Pruefplatz":pruefplatz, "Auftrag":auftrag, "Gueltig":gueltig});
If you are having a lot of parameters to pass to the action method, create a model which encompasses these parameters. For example, I have created MyParamModel class here below:
public class MyParamModel
{
//Your parameters go here
public int IntProperty { get; set; }
public string StringProperty { get; set; }
}
Then modify the action method to accept this class as parameter.
public ActionResult Action(MyParamModel model)
Modify the load call in the script to pass information to the url like this.
$(item).load(url, {"IntProperty":1, "StringProperty": "test"});
Once you have the model on the controller end, you can validate it accordingly.
Hope this helps. If it does, mark this as answer.
json is passed from browser using POST method to ASP.NET MVC4 application controller in server.
It contains properites from which 3 are arrays of 0.. 20 elements (in code below all of them
have only 1 element).
How to parse this json in C# ?
I tried controller with signature
public JsonResult RegisterSales(Sale mysale)
but mysale properties are not assigned.
passed json:
{ "id":"sale1",
"sale_date":"2013-11-10 19:20:44"
"taxes":[{"id":"km20pr","name":"20%","rate":0.2}],
"products":[{"id":"prod1",
"sale_id":"sale1",
"register_id":"register1",
"quantity":"1.00000"}],
"payments":[{"id":"payment1",
"sale_id":"sale1",
"register_id":"register1",
"amount": 0
}]
}
It should parsed to C# structure something like
public class Sale
{
public string id;
public DateTime sale_date;
public Tax[] taxes;
public Product[] products;
public Payment[] payments;
}
public class Tax
{
public string id, name;
public decimal rate;
}
public class Product
{
public string id, sale_id, register_id;
public decimal quantity;
}
public class Payment
{
public string id, sale_id, register_id;
public decimal amount;
}
Use NewtonSoft JSON Deserialize, like so:
class School
{
public string student;
public object[] data;
}
School datum = JsonConvert.Deserialize<School>(jsonStr);
//Do stuff with datum...
Enjoy.
You need to post data with correct content type. In this case it's application/json. MVC chooses correct binding mode based on the content type used to send data to a server.
The best thing to do is to have the same name for the json as for your accepting variable "mysale".
Example:
"mysale": { "id":"sale1",
"sale_date":"2013-11-10 19:20:44"
"taxes":[{"id":"km20pr","name":"20%","rate":0.2}],
"products":[{"id":"prod1",
"sale_id":"sale1",
"register_id":"register1",
"quantity":"1.00000"}],
"payments":[{"id":"payment1",
"sale_id":"sale1",
"register_id":"register1",
"amount": 0
}]
}
You can do this by adding the name in the AJAX call by so:
$.ajax({
...,
...,
data: JSON.stringify({mysale:data}),
...,
...
});
Now it will accept your JSON.
The reason for this is that the JSON posted will be viewed as a post value, and just like with a normal form you can catch this value by its name.
So to answer your question: adding {get;set;} is not the best way to go.
if so, how should i pass the parameter? would a string matching the enum name be ok? This would be handy if I was passing a dropdown box that matched enumerated items.
It would be useful to use a solution presented in this answer if I could just as easily bind to the enum when I submit the data back.
Yes, when having a controller like:
enum MyAction { Lalala }
public ActionResult Index(MyAction action) { ... }
You can just do Index/Lalala, and everything works fine.
If you need more complex binding (like mapping a certain string value to a complex class), use something like StructureMap.
It gets even better you can also pass Enum as get parameter
#Html.ActionLink("Email Quote", "UnitDetails", "Journey", new { product = product.ProductTitle, button = "email" }, new { #class = "btn btn--main btn--main-orange" })
that ends up following url: http://localhost:50766/UnitDetails?product=Your%20quote&button=email
Action method that accepts looks like this:
[SessionTimeout]
public ActionResult UnitDetails(QuoteViewModel viewModel)
QuoteViewModel and enum:
public class QuoteViewModel : IQuoteViewModel
{
public QuoteViewModelProducts Products { get; set; }
public bool HasDiscount { get; set; }
public string Product { get; set; }
public DetailButtonType Button { get; set; }
}
public enum DetailButtonType
{
Buy,
Callback,
Email
}
What I love most is even if you pass enum parameter and value as lowercase it maps correctly to Uppercase property and Value, which makes my grin profusely.