How to pass a dynamic value to another view page - asp.net-mvc-3

anybody can teach me how to set default value in VIEW page?
the thing I want is something like :
#Html.HiddenFor(x => x.MemAd , value="M")
and
How can I pass dynamic value to another view page by using session?

You do this in the controller action rendering this view:
public ActionResult SomeAction()
{
MyViewModel model = ...
model.MemAd = "M";
return View(model);
}
and in the corresponding view:
#model MyViewModel
...
#Html.HiddenFor(x => x.MemAd)
will generate:
<input type="hidden" name="MemAd" id="MemAd" value="M" />

Related

partial views to get data and then post the results to save in database

I am very new to MVC, let me try to explain my scenario in plain simple English:
I have an strongly typed mvc form/page (Product.cshtml) with a model, say ProductViewModel.
This page has got two search buttons, one to search and bring the items to be added to the Product and other to bring in the location, most probably partial views.
Now, what I want is that these search results work in ajax form without complete post back, and then the results of these searches (items and location) should be posted back using model binding to the form when user clicks on the submit button.
What could be the best way of achieving this functionality?
Immediate responses will be well appreciated.
I thought, its good to share the complete code for clarity:
I have one form(Service1.chtml) that has a partial view to display users(_TestUser a partial view:read only), then another partial view(_PlotServiceRequestData) that should have a field to search the plot and bring back the details lke its owner name and landuser etc.
Then when I click on submit button of the main form, I should be able to read all data(main form) + new data from _PlotServiceRequestData partial view and save all data to database.
I was trying one more option, that is, to use #Ajax.ActionLink on Service1.cshtml to call the _GetPlotDetails method and then store partial view data in TempData, so that it is available to the form when users clicks on "Submit" button of Service1.cshtml, is this a right approach?, if I use ajax.BeginForm inside partial view then the data is posted to the
Service1 controller method which is actually to save the form data and not to update the partialview and in this method even I am not getting model data of the partial view.
Sevice1.cshtml:
#model ViewModels.TestViewModel
#{
ViewBag.Title =
"Service1";
}
#
using (Html.BeginForm())
{
#Html.LabelFor(m => m.Title)
#Html.EditorFor(m => m.Title)
#Html.Partial(
"_TestUser", Model)
<div id="RequestPlotData">
#Html.Partial(
"_PlotServiceRequestData", Model.requestData)
</div>
<button type="submit">Save Form</button>
}
#section Scripts {
}
_PlotServiceRequestData.cshtml:
===============================
#model ViewModels.PlotServicesRequestDataViewModel
<
div id="RequestPlotData">
#
using (Ajax.BeginForm("_GetPlotDetails", "Test", new AjaxOptions { UpdateTargetId = "RequestPlotData", Url = Url.Action("_GetPlotDetails","Test") }))
{
<h1>Request Details</h1>
 
<div>
#Html.LabelFor(m => m.plotAddress)
#Html.EditorFor(m => m.plotAddress)
<input type="submit" name="submit" value="Ajax Post" />
</div>
<div>
#Html.LabelFor(m => m.LandUser)
#Html.EditorFor(m => m.LandUser)
</div>
<div>
#Html.LabelFor(m => m.OwnerName)
#Html.EditorFor(m => m.OwnerName)
</div>
}
</
div>
CONTROLLER:
==========
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.Mvc;
namespace
TestNameSpace
{
public class TestController : Controller
{
//
// GET: /Test/
public ActionResult Service1()
{
Injazat.AM.mServices.
LocalDBEntities context = new Injazat.AM.mServices.LocalDBEntities();
TestViewModel model =
new TestViewModel() { user = context.Users.First(), Title = "Land Setting Out",
requestData =
new PlotServicesRequestDataViewModel() { ServiceNumber ="122345", TransactionDate="10/10/2033" } };
return View(model);
}
[
HttpPost()]
public ActionResult Service1(TestViewModel model)
{
PlotServicesRequestDataViewModel s = (PlotServicesRequestDataViewModel)TempData[
"Data"];
TestViewModel vm =
new TestViewModel() { user = model.user, requestData = s, Title = model.Title };
return View(vm);
 
}
[
HttpGet()]
//public PartialViewResult _GetPlotDetails(string add)
public PartialViewResult _GetPlotDetails(PlotServicesRequestDataViewModel requestData)
{
//PlotServicesRequestDataViewModel requestData = new PlotServicesRequestDataViewModel() { plotAddress = add};
requestData.OwnerName =
"owner";
requestData.LandUser =
"landuser";
TempData[
"Data"] = requestData;
return PartialView("_PlotServiceRequestData", requestData);
}
}
}
You can probably use the jQuery Form plugin for this. This makes the process of posting the data from your form back to the server very easy. The form would post to an action that would return a partial view that you can then push into your UI.
To make this easier, jQuery form actually has a "target" option where it will automatically update with the server response (ie. the partial view returned from your search action).
View
<form id="searchForm" action="#(Url.Action("Search"))" method="POST">
<input name="query" type="text" /> <!-- order use Html.TextBoxFor() here -->
<input type="submit" />
</form>
<div id="result"><!--result here--></div>
Javascript
$('#searchForm').ajaxForm({
target: '#result'
});
Controller
public ActionResult Search(string query)
{
// Do something with query
var model = GetSearchResults(query);
return Partial("SearchResults", model)
}
This should hopefully help you to get on the right track. jQuery Form is a good plugin and is the main thing you should look into for ajaxifying your form posts back to the server. You might also want to look into using jQuery's $.post and $.ajax functions, but these require slightly more work.

passing data from view to controller on asp.net mvc 3

i have problem to pass data from view to controller , i have view that is strongly typed with my viewmodel "TimeLineModel", in the first i passed to this view my viewmodel from action on my controller
public ActionResult confirmation(long socialbuzzCompaignId)
{
return View(new TimeLineModel() { socialBuzzCompaignId = socialbuzzCompaignId, BuzzMessages = model });
}
with this i can get info from my action and display it on view , but i have other action POST which i won't get my view model to do some traitement
[HttpPost]
public ActionResult confirmation(TimeLineModel model)
{
}
i can get some propretie of the model but in others no , for example i can get the properti "socialBuzzCompaignId" of model , but other propertie like "IEnumerable BuzzMessages" i can't get it , i dont now why !!
this is the content of my view
#model Maya.Web.Models.TimeLineModel
#{
ViewBag.Title = "confirmation";
}
#using (Html.BeginForm())
{
<h2>confirmation</h2>
<fieldset>
#foreach (var msg in Model.BuzzMessages)
{
<div class="editor-label">
#msg.LongMessage
</div>
<br />
}
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
You need to include BuzzMessages properties within a form element. Since it's not editable, you'd probably want to use hiddens. There are two ways to do this. Easiest is instead of doing a foreach loop, do a for loop and insert them by index.
#for (int i =0; i<Model.BuzzMessages.Count(); i++v)
{
<div class="editor-label">
#Model.BuzzMessages[i].LongMessage
#Html.HiddenFor(m => m.BuzzMessages[i].LongMessage);
</div>
<br />
}
but to do this you'd need to use an IList instead of an IEnumerable in your view model to access by index.
Alternatively, you could create an Editor Template named after your BuzzMessages class (whatever its name is).
#model BuzzMessagesClass
#Html.HiddenFor(m => m.LongMessages)
<!-- Include other properties here if any -->
and then in your main page
#Html.EditorFor(m => m.BuzzMessages)
Check out http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/ or search stack overflow if the details of editor templates confuse you.
Just like any HTML POST method, you have to get the data back to the Controller somehow. Just simply "showing" the data on the page doesn't rebind it.
You have to put the data in an input (or a control that will post back) to the appropriate model property name.
So, if you have a model property with name FirstName and you want this data to be rebound to the model on POST, you have to supply it back to the model by placing an "input hidden" (or similar control that postbacks) with the ID of FirstName will rebind that property to the model on POST.
Hope that explains it.
#foreach (var msg in Model.BuzzMessages)
{
<div class="editor-label">
#msg.LongMessage
<input type="hidden" name="BuzzMessages.LongMessage" value="#msg.LongMessage" />
</div>
}
It will post array of LongMessages. Get values like this:
[HttpPost]
public ActionResult confirmation(TimeLineModel model, FormCollection collection)
{
var longMessages = collection["BuzzMessages.LongMessage"];
}

Using submit and text to pass a value to a controller

I am a begginer with asp.net mvc 3. I want to create a page where an user can enter a search item and retrieve the data from database. I have created the database. I have created the controller which is:
public ActionResult SearchIndex(string id)
{
string searchString=id;
var search = from m in db.Searches
select m;
if (!String.IsNullOrEmpty(searchString))
{
search = search.Where(s => s.Name.Contains(searchString));
}
return View(search);
}
I want to pass the value from view page to the above controller. What should be the code in view page to enter an item to search from above mentioned controller?
So create your view with a form inside... something like this:
#using (Html.BeginForm())
{
<label>Search:</label>
<input type="text" name="searchString" />
<input type="submit" name="submit" />
}
Then in your controller you can use the FormCollection object to grab your searchString like this:
[HttpPost]
public ActionResult SearchIndex(FormCollection formCollection)
{
string searchString = formCollection["searchString"];
...
}

MVC3: Batch edit attendence and pass the model to a Review Action

I have an Index.cshtml view:
#model AttendenceModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm("VisOppsummering", "Attendences", new { AttendenceModel = Model }, FormMethod.Post))
{
#Html.DisplayFor(m => m.ClassName)
#Html.EditorFor(m => m.Attendences)
<button type="submit">Next</button>
}
and an Editor Template Attendence.cshtml:
#model Attendence
#Html.DisplayFor(m => m.Student.Name)
#Html.RadioButtonFor(m => m.Attended, true, new { id = "attendence" })
Teachers can check off all students that attended school and than pass on the changed model to "Review" action where they can review all the attendended and not attended students and Submit. I want to use MVC best practice for this. AttendenceModel has several properties and a generic list Attendences which is List.
I've tried following without success. Model is empty.:
[HttpPost]
public ActionResult Review(AttendenceModel model)
{
if (TryUpdateModel(model))
{
return View(model);
}
}
The following argument to your BeginForm helper is meaningless:
new { AttendenceModel = Model }
you cannot pass complex objects like this. Only simple scalar values. You could use hidden fields in your form for all properties that cannot be edited and visible input fields for the other. Or even better: use a view model which will contain only the properties that can be edited on the form and an additional id which will allow you to fetch the original model from the database and using the TryUpdateModel method update only the properties that were part of the POST request:
[HttpPost]
public ActionResult Review(int id)
{
var model = Repository.GetModel(id);
if (TryUpdateModel(model))
{
return View(model);
}
...
}
as far as the view is concerned it would become:
#model AttendenceViewModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm("Review", "SomeControllerName"))
{
#Html.HiddenForm(x => x.Id)
#Html.DisplayFor(m => m.ClassName)
#Html.EditorFor(m => m.Attendences)
<button type="submit">Next</button>
}

ViewModel has no properties set in Model using HttpPost Create method

I have a simple MVC3 app with an EF4 Model
Log
.Name
.CreatedDate
.LogTypeId
LogTypes
.Id
.Description
and a ViewModel
LogViewModel
Log MyLog
List<SelectListItem> Options
LogViewModel(){
Log = new Log();
}
This displays in my view correctly and I can edit/update the values, display the drop down list and set the name to "MyTestValue".
However, in my controller's HttpPost Create method the properties for logVm.Log are not set?
[HttpPost]
public ActionResult Create(LogViewModel logVm){
logVm.Log.Name == "MyTestvalue"; //false - in fact its null
}
What am I doing wrong?
That's probably because in your edit form you don't have corresponding values. So if yuor view is strongly typed to LogViewModel the form input names must be appropriately named:
#model LogViewModel
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(x => x.Log.Name)
#Html.EditorFor(x => x.Log.Name)
</div>
<div>
#Html.LabelFor(x => x.Log.SomeOtherProperty)
#Html.EditorFor(x => x.Log.SomeOtherProperty)
</div>
...
<input type="submit" value="OK" />
}
sop that when the form is submitted the POSTed values look like this:
Log.Name=foo&Log.SomeOtherProperty=bar
Now the default model binder will be able to successfully bind your view model. Also make sure that the properties you are trying to assign are public and that have a setter.
The controller method should have a property named model
[HttpPost]
public ActionResult Create(LogViewModel **model**){
**model**.Log.Name == "MyTestvalue"; //true }

Resources