I want to pass the data from controller to my modal class.
Here is a test example of what I want to do,
I can't publish my code here as my code is very large in number of lines.
[HttpPost]
public ActionResult testdata()
{
string testdata = "send test data";//this data i want to pass to my model class
return View();
}
as my modal class is inserting the same data into database
public bool inserttestdata()
{
cmd = new SqlCommand();
cmd.Parameters.AddWithValue("#test", "test data want here");//here I want to use the data which i declared in my controller
int i = dbf.ExecuteSP("testproc", cmd);
if (i >= 1)
return true;
else
return false;
}
This is just a test data, my actual code is very large and the data which I want to insert is dynamic and not static.
Where are you calling inserttestdata() from? You need to pass the testdata as a parameter to this method.
Here for example : public bool inserttestdata(string testdata)
then call inserttestdata(testdata)
You can store data to model simply like this-
MyModel model = new MyModel();
model.someVariable = "your data";
Where your model would look like-
public class MyModel
{
public string someVariable {get; set;}
}
Related
I have a _LoginPartial View and want to send data to it by ViewBag, but the Controller that I'am sending data from, doesn't have a View.
public PartialViewResult Index()
{
ViewBag.sth = // some data
return PartialView("~/Views/Shared/_LoginPartial.cshtml");
}
This code didn't work for me.
It seems you're expecting this Index action to be called when you do: #Html.Partial('_LoginPartial'). That will never happen. Partial just runs the partial view through Razor with the current view's context and spits out the generated HTML.
If you need additional information for your partial, you can specify a custom ViewDataDictionary:
#Html.Partial("_LoginPartial", new ViewDataDictionary { Foo = "Bar" });
Which you can then access inside the partial via:
ViewData["Foo"]
You can also use child actions, which is generally preferable if working with a partial view that doesn't need the context of the main view. _LoginPartial seems like a good candidate, although I'm not sure how exactly you're using it. Ironically, though, the _LoginPartial view that comes with a default MVC project with individual auth uses child actions.
Basically, the code you have would already work, you would just need to change how you reference it by using Html.Action instead of Html.Partial:
#Html.Action("Index")
Notice that you're calling the action here and now the view.
You can always pass data directly to the partial view.
public PartialViewResult Index()
{
var data = // some data
return PartialView("~/Views/Shared/_LoginPartial.cshtml", data);
}
Pass multiple pieces of data
public class MyModel
{
public int Prop1 { get; set; }
public int Prop2 { get; set; }
}
public PartialViewResult Index()
{
var data = new MyModel(){ Prop1 = 5, Prop2 = 10 };
return PartialView("~/Views/Shared/_LoginPartial.cshtml", data);
}
I passed viewBag data to my partial view like below, and I converted that viewBag data object to JSON in my partial view by using #Html.Raw(Json.Encode(ViewBag.Part));
my code sample is given below.
public async Task<ActionResult> GetJobCreationPartialView(int id)
{
try
{
var client = new ApiClient<ServiceRepairInspectionViewModel>("ServiceRepairInspection/GetById");
var resultdata = await client.Find(id);
var client2 = new ApiClient<PartViewModel>("Part/GetActive");
var partData = await client2.FindAll();
var list = partData as List<PartViewModel> ?? partData.ToList();
ViewBag.Part = list.Select(x => new SelectListItem() {Text = x.PartName, Value = x.Id.ToString()});
return PartialView("_CreateJobCardView" ,resultdata);
}
catch (Exception)
{
throw;
}
}
Here i have passed both model and viewBag .
First off, the code in your question does not run. When you do #Html.Partial("_SomeView") the Index() method you have there does not run. All #Html.Partial("_SomeView") does is render _SomeView.cshtml in your current view using the current view's ViewContext.
In order to get this to work you need a bit of functionality that's common to all the controllers in your project. You have two options: extension method for ControllerBase or a BaseController that all the controllers in your project inherit from.
Extension method:
Helper:
public static class ControllerExtensions
{
public static string GetCommonStuff(this ControllerBase ctrl)
{
// do stuff you need here
}
}
View:
#ViewContext.Controller.GetCommonStuff()
BaseController
Controller:
public class BaseController : Controller
{
public string GetCommonStuff()
{
// do stuff you need here
}
}
Other controllers:
public class SomeController : BaseController
...
...
View:
#((ViewContext.Controller as BaseController).GetCommonStuff())
I have a tuble like this as model.
#model Tuple<Urun,List<UrunKatagori>>
inside the view I need to pass those data to controler.
here is the my button.
Html.X().Button().Text("Guncelle").Icon(Icon.PageSave)
.DirectEvents(de =>
{
de.Click.Url = "Urunler/Guncelle";
de.Click.ExtraParams.Add(new Parameter { Name = "Urun", Value ="Model.Item1", Mode = ParameterMode.Raw });//Iguess here is wrong
})
and my controller
[HttpPost]
public ActionResult Guncelle (Urun Urun){
Urun_BLL urun_bll = new Urun_BLL();
// urun_bll.Update(mdl);
X.Msg.Notify(new NotificationConfig
{
Icon = Icon.Accept,
Title = "Working",
Html =Urun.Ad.ToString()//I need to get data here
}).Show();
return this.Direct();
}
I strongly suggest that you create a viewmodel class, rather then passing a Tuple e.g.
public class GuncelleViewModel
{
public Urun Urun { get ;set; }
public List<UrunKatagori>> UrunKatagori { get; set; }
}
Then you can pass that to the view like so:
[HttpPost]
public ActionResult Guncelle (Urun Urun)
{
Urun_BLL urun_bll = new Urun_BLL();
// urun_bll.Update(mdl);
X.Msg.Notify(new NotificationConfig
{
Icon = Icon.Accept,
Title = "Working",
Html =Urun.Ad.ToString()//I need to get data here
}).Show();
var viewModel = new GuncelleViewModel()
viewModel.Urun = Urun;
viewModel.UrunKatagori = // TODO - However you get the categories.
return View(viewModel);
// this.Direct(); What does this.Direct() do? Replace it with calling the view instead, much cleaner.
}
In the view, use the following model
#model GuncelleViewModel
Useing a viewmodel class, which is associated one-to-one with a view file (*.cshtml), is a very good practise. It can help keep your design clean and more flexible, rather then passing specific data types, such as Tuple.
I have a view which contains data from 4 tables from the database.
Do i need to define all of those fields in my model? so that i can use them in my view like :-
#model.fieldFromTable1
#model.fieldFromTable2
#model.fieldFromTable3
#model.fieldFromTable4
The quick answer is yes. You can probably think of your model more as a ViewModel. Not an actual model from your database.
In your controller you would just populate the ViewModel from your database models
MyViewModel.cs
//put whatever properties your view will need in here
public class MyViewModel
{
public string PropertyFromModel1 {get; set;}
public string PropertyFromModel2 {get; set;}
}
MyController.cs
public ActionResult MyAction()
{
//the only job your action should have is to populate your view model
//with data from wherever it needs to get it
Model1 model = GetFirstModelFromDatabase();
Model2 model2 = GetSecondModelFromDatabase();
MyViewModel vm = new MyViewModel
{
PropertyFromModel1 = model.MyProperty;
PropertyFromModel2 = model2.MyProperty;
}
return View(vm);
}
MyAction.cshtml
#Model.PropertyFromModel1
#Model.PropertyFromModel2
It's actually pretty standard practice to not use your raw domain models in your views, because I would say that typically don't match up exactly to what you want to display.
I work with asp MVC 4. I have a single controller and I want to share the same object between his functions. I thought about a data member but it doesn't work. Here is my code :
public class MyController : Controller
{
public MyObject obj;
public ActionResult Index()
{
obj = new MyObject();
this.obj.GetData(); // Fill my object
return View();
}
public ActionResult MyFunction()
{
Console.Write(this.obj); // Always null
return View();
}
}
Is it possible to keep this object between functions ? I used to create TempData ou ViewBags for sharing data but I'm not sure if it's the right way to manage big objects.
It is null because MVC framework create a new controller to handle different requests, hence the obj is also different.
If you make your Object singleton or simply make it static, it will work.
public static MyObject obj;
Try this:
public class MyController : Controller
{
public MyObject obj = new MyObject();
public ActionResult Index()
{
this.obj.GetData(); // Fill my object
return View();
}
public ActionResult MyFunction()
{
Console.Write(this.obj); // Always null
return View();
}
}
This will stop your null error.
If you want to save data between postbacks, you will need to look into persistent data storage such as a SQL based database.
I have the following controller in an ASP.Net WebApi project.
The model is generated with Entity Framework.
public class CategoriesController : ApiController
{
private eLearningDbEntities context = new eLearningDbEntities();
// GET api/Categories
public IEnumerable<Categories> GetCategories()
{
var query = from c in context.Categories
select c;
return query;
}
}
When call the controller from the browser I get the following result, but I want to get only the properties of the Model, not all the context properties. Any ideas what is wrong?
<ArrayOfCategories xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/eLearning.DomainModel">
<Categories xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" z:Id="i1">
<EntityKey xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Data" xmlns="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses" z:Id="i2">
<d3p1:EntityContainerName>eLearningDbEntities</d3p1:EntityContainerName>
<d3p1:EntityKeyValues>
<d3p1:EntityKeyMember>
<d3p1:Key>ID</d3p1:Key>
<d3p1:Value xmlns:d6p1="http://www.w3.org/2001/XMLSchema" i:type="d6p1:int">1</d3p1:Value>
</d3p1:EntityKeyMember>
</d3p1:EntityKeyValues>
<d3p1:EntitySetName>Categories</d3p1:EntitySetName>
</EntityKey>
<ID>1</ID>
<Name>e-Business</Name>
</Categories>
<Categories xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" z:Id="i3">
<EntityKey xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Data" xmlns="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses" z:Id="i4">
<d3p1:EntityContainerName>eLearningDbEntities</d3p1:EntityContainerName>
<d3p1:EntityKeyValues>
<d3p1:EntityKeyMember>
<d3p1:Key>ID</d3p1:Key>
<d3p1:Value xmlns:d6p1="http://www.w3.org/2001/XMLSchema" i:type="d6p1:int">2</d3p1:Value>
</d3p1:EntityKeyMember>
</d3p1:EntityKeyValues>
<d3p1:EntitySetName>Categories</d3p1:EntitySetName>
</EntityKey>
<ID>2</ID>
<Name>SADE</Name>
</Categories>
</ArrayOfCategories>
Thank you!
You shouldn't be passing back your database entity directly, but instead creating a view model that you can pass back that isolates the message to only the fields that you care about receiving on the client end. e.g.
// Create a View Model to hold appropriate properties
public class MyViewModel
{
public string PropertyA {get; set;}
public string PropertyB {get; set;}
}
...
// Map your entity to the View Model and return it.
var viewModel = context.Categories.Select(
e=>new MyViewModel(){
PropertyA = e.SomeProperty,
PropertyB = e.AnotherProperty
});
return viewModel;