Tag Archives: CheckBox

CheckBox

[RESOLVED]How to pass records between Views?

I have a table of records and a submit button.
How do i Pass those records from one view to another another view while clicking the Submit Button?

Thanks in advance!

From the view, the data goes to the respective controller. That’s the route. From that controller you can server your desired view and pass the data to it as model object.

Using the following in the controller action method:

return View("AnotherView",ModelObject);

How did your table initially populate with records?  Action and View code would be useful

Do you mean view to view or from one controller to another controller? What I get from the question is that on submit you will be calling another page/controller?

If it is controller to another controller then use tempdata. 

How to pass data in ASP.Net MVC app refer below

http://msdn.microsoft.com/en-in/library/dd394711(v=vs.100).aspx

there is no direct passing of data between views. a view is html that is returned to the browser. when that view contains an anchor (link) to request a new html page, data can be passed via the query string. if its a form submit, then the form fields are
passed. MVC’s data binder will bind these field to the action parameters (often a model).

so to pass data from one form to another usually requires a form, and submit. all data must be in a <input>, <select> or <textarea>. to pass a complete object, each property must be written to a form field, or that property will not be in the postback data
(which is a name/value collection).

if you are writing a javascript application, then there are more ways to pass data via ajax or dynamic forms, but thats different

You cannot pass data directly from view to another view on submit

you submit data to action and action returns the view by passing the data

Can you give me any sample code on how to pass list of records from one table to another table?

from html table to html table?

or

db table to db table?

From HTML table to another HTML table

check this

<table id="table1" border="1">
    <tr> <td>ID</td> <td>Name</td></tr>
    <tr> <td>1</td><td>Name1</td> <td><input type="checkbox" id="movebutton" value="Move" onclick="MoveRow(this)" /></td> </tr>
    <tr> <td>2</td><td>Name2</td> <td><input type="checkbox" id="movebutton" value="Move" onclick="MoveRow(this)" /></td> </tr>
    <tr> <td>3</td><td>Name3</td> <td><input type="checkbox" id="movebutton" value="Move" onclick="MoveRow(this)" /></td> </tr>
    <tr> <td>4</td><td>Name4</td> <td><input type="checkbox" id="movebutton" value="Move" onclick="MoveRow(this)" /></td> </tr>
</table>
<br />
<br />
<br />
<table id="table2" border="1"><tr> <td>1</td><td>Name1</td> <td></td></table>

    <script>
        function MoveRow(movebutton) {
            var table2 = document.getElementById("table1");
            var table2 = document.getElementById("table2");
            var rowchecked = movebutton.parentNode.parentNode;
            var rowcheckedClone = rowchecked.cloneNode(true);
            var checked = movebutton.checked;
            var foundIndex = -1;
            rowcheckedClone.deleteCell(0);
            rowcheckedClone.deleteCell(1);

            for (var i = 0; i < table2.rows.length; i++) {
                if (rowcheckedClone.isEqualNode(table2.rows[i])) {
                    foundIndex = i;
                }
            }
            if (checked) {
                if (foundIndex == -1)
                    table2.appendChild(rowcheckedClone);
            }
            else {
                if (foundIndex > -1)
                    table2.deleteRow(foundIndex);
            }
        }
    </script>

[RESOLVED]List<string> passed in ViewBag gets with “System.Collections.Generic.List`1[System.String]”

I have a link to another controller and I want to pass a list of strings.

FirstController.cs

I have list of records in table with checkbox in each row, List of string values are selected by checking the checkbox.

public ActionResult Select(bool isChecked, String id)
        {
            var selectList = (List<String>)HttpContext.Session["SelectList"] ?? new List<String>();
            if (isChecked && !selectList.Contains(id))
            {
                selectList.Add(id);
            }
            else if (!isChecked && selectList.Contains(id))
            {
                selectList.RemoveAll(s => s == id);
            }
            ViewBag.selectList = selectList;
            return Content("OK");
        }

This list of string values i am passing to another SecondController.cs using ‘ViewBag’

public ActionResult AddSitesToUser(string returnUrl,string selectList, int userId = 0)
        {
            ViewBag.selectList = selectList;
}

My View:

(Html.BeginForm("AddSitesToUser", "User", new { returnUrl = ViewBag.returnUrl,selectList=((List<string>)ViewBag.selectList )})

In my FirstController.cs the list of ViewBag.selectList = selectList; created properly, but if i pass those list of strings to SecondController.cs instead of returning list of strings it gives me ‘"System.Collections.Generic.List1[System.String]"

Any idea on what I’m doing wrong?

Thanks

This is because you are using this within the RouteValues parameter of the BeginForm() method, which will populate QueryString variables for the action attribute on the Form itself.

If you are storing a collection of strings within the ViewBag, ASP.NET isn’t going to know how to display this within the URL so it uses "System.Collections.Generic.List" as it was passed a string and that’s the only way it knows how to interpret it.

You might try storing a comma-delimited string within ViewBag which might be able to be passed along more easily as follows :

// When storing your values in the SelectList, consider using a comma-delimited string (e.g. "A,B,C,D,E,F")
ViewBag.selectList = String.Join(",",selectList.Items.Cast<string>().ToArray());

This will add this comma-delimited string to your form properly when it loads your selectList variable : 

(Html.BeginForm("AddSitesToUser", "User", new { returnUrl = ViewBag.returnUrl,selectList=ViewBag.selectList )})

Then when your AddSitesToUser method is posted to, you can pull your collection out of the QueryString and properly split it back into a collection :

public ActionResult AddSitesToUser(string returnUrl,string selectList, int userId = 0)
{
     // Retrieve your list
     List<string> list = selectList.Split(',').ToList();
}

Tried with your solution, but still showing same 

“System.Collections.Generic.List`1[System.String]”

That’s shouldn’t be happening, as the line where you actually set your ViewBag should store a string into it (and not a collection) :

ViewBag.selectList = String.Join(",",selectList.Items.Cast<string>().ToArray());

when you add routes values to the form, ToString() is called on the value to make it a string. for List<> (and most classes). the to string just returns the class name. you need to convert the list to a string value, that your controller can later parse.

[RESOLVED]How to save dropdown selected text into database using EF In MVC4?

Hi Friends ,

           I would like to know how to save  Dropdown selected text  and Checkbox checked value in data base using EF.Can anyone provide example Code ?

Thx in advance 

-Ernesto Karthik

 

HI  Dharmesh ,

                       I have  binded the dropdown values in the dropdown. i would like to save the selected Text in the dropdown in another table.How to do that using EF 

Thx ,

-Ernesto Karthik

 

 

Hi Karthik ,

I will suggest use Begin form in your view , so you can pass selected values to your controller/ action. Once you get this value in  Post action, you can call EF method or DAL method.

For example :

@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post))
    {

/// Dropdown 1

/// Dropdown 2
<input type="submit" value="Html PsBk Click" /> }

Now in "ActionName" you need to write code to read this param.

[HttpPost]
        public ActionResult ActioName(PersonnelModel Pmodel)
        {
   // Read model data from this param ex. Pmodel.dropdown1 // Pmodel.dropdown2         
----
-- }

For more details : http://msdn.microsoft.com/en-us/library/dd505244(v=vs.118).aspx

1. Entity class must have properties to hold the text and value

2. In View, keep hidden with name of above text property

3. In View, keep dropdown for above value property

3. Update the hidden value wit dropdown selecteditem on selection of dropdown at client side

then the text also gets posted

EF creates POCO classes of your database.  MVC allows you to send those objects to the user to edit and post.  In your controller you can take an instance of that class like this:

public ActionResult SavedPerson(Person person){
int rowssaved = 0;
//first see if model state is valid
if (ModelState.IsValid){

using (var db = new myEFEntities()){
   db.Person.Add(person);
   rowsaved=db.SaveChanges();
}
var results = new VMSavedPerson(person, rowsaved);
return View(SavedPerson);
}

[RESOLVED]How to get the id of anchor tag created in mvc razor view.

Hello,

I am new for MVC, been trying to send the id of the anchor tag clicked to the controller.

<table width="100%">
                    <tr>                  
                       
            @foreach (var item in ViewBag.Schedules as List<BMS.DataAccessLayer.Schedules>)
                {    <td>
                             <span class="span12">
                   <a href="@Url.Action("AgentHomePost")"><img src="@Url.Content(@item.IconUrl.ToString())" width="150px" height="150px" name="@item.BreakTypeName" class=" wip" id="@item.BreakTypeName" alt="@item.BreakTypeName"/> </a> 
                   
                 </span>
                        </td>
                   
                }    
                         </tr>
                </table>
 public ActionResult AgentHomePost(string Id)
        {
            // blah blah
            return RedirectToAction("AgentHome", "Home");
        }

I assume that you’ve validated and can see the id’s you want (View Page Source).

The next thing you need to do it put some selection mechanism for the user and encapsulate it all in a @Html.BeginForm block with a submit form.  I would personally not construct the view in the view, I would construct the infrastructure for the view in
the viewmodel and pass a strongly typed view using that viewmodel to the view.  But that’s my preference.

This
post
shows a good example.

instead of using <a> tag, try using @html.action, you can pass the input parameters as route values of action link

@Html.ActionLink("Back
to List"
,
"AgentHomePost",
new
{ id=item.BreakTypeName})

To get the image, you need to place a <div> tag around @html.ActionLink and use a css class whose bakground
is the image, and set the width of div to the images width

<div
class="ActiveNav">@Html.ActionLink("Back
to List"
,
"AgentHomePost",
new
{ id=item.BreakTypeName})
</div>

.ActiveNav

{width:120px;height:23px;background:url(images/Nav.png)
no-repeat;padding-top:7px;padding-left:10px;}

you might have to put separate css for different type of url.

 

Hi,

You have to use the overload version of the Url.Action(string,object)

In your case, it has to be:
<a href=’@Url.Action("AgentHomePost",new{Id=item.BreakTypeName})’>

check this for overloaded method details:
http://msdn.microsoft.com/en-us/library/dd460294%28v=vs.118%29.aspx

Hi Ashim,

@Url.Action() is the right solution for this issue. 

let me know if any other issue. 

[RESOLVED]MVC Grid List and details redirect using Web API and Javascript

Using MVC, Web API, and JavaScript Create a website that has the following:

1. Landing page that displays a list of machines (name, description)

2. Each machine has a link to show its details. (Use Asp.Net MVC).

3. Display machine details and let the user enable or disable it (Use Asp.Net Web API).

4. Next to the machine details, show a list of "measurements" for the machine by polling the server every 3 seconds and append the measured information which is returned from the server (random number) to the list. (Use JavaScript + Web API).

Notes: Machines must be persisted in memory, having an initial set of 10 machines.

Data points for each machine don’t have to be persisted. Each machine has the following properties: Id, description and status (enabled, disabled)

Use bootstrap or similar for layout and styling. 

Can someone give me the code for bove or point me to rsources on the web . I am completely new to MVC and any help is welcome

Thanks

ROHITJGC

Can someone give me the code for bove or point me to rsources on the web . I am completely new to MVC and any help is welcome

THis is a basic application. Please see tutorials from http://www.asp.net/mvc

Hi ROHITJGC,

ROHITJGC

1. Landing page that displays a list of machines (name, description)

2. Each machine has a link to show its details. (Use Asp.Net MVC).

You could refer to this article below:

# MVC Music Store

http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-1

ROHITJGC

3. Display machine details and let the user enable or disable it (Use Asp.Net Web API).

Just need to update the record in the database

ROHITJGC

4. Next to the machine details, show a list of "measurements" for the machine by polling the server every 3 seconds and append the measured information which is returned from the server (random number) to the list. (Use JavaScript + Web API).

Using jQuery AJAX to request the data.

ROHITJGC

Notes: Machines must be persisted in memory, having an initial set of 10 machines.

You could store the data in the session

ROHITJGC

Use bootstrap or similar for layout and styling. 

Please refer to:

# Bootstrap Overview

http://getbootstrap.com/css/

You need to try it by yourself, if you have the issues, please create the thread for each issue.

Best Regards

Starain

I have completed the first 2 points 

3. Display machine details and let the user enable or disable it (Use Asp.Net Web API).

First they dont want check boxes but Enable and Disable Buttons , I saw on below site 

http://jameschambers.com/2012/07/bootstrapping-mvc-say-no-to-checkboxes/  but getting error

0x800a1391 – JavaScript runtime error: ‘$’ is undefined

Also  How to use ASP.net Web API to do the edits??????

4. Next to the machine details, show a list of "measurements" for the machine by polling the server every 3 seconds and append the measured information which is returned from the server (random number) to the list. (Use JavaScript + Web API).

I have no idea about polling the server every 3 seconds what does this mean and How to append this information to a list

Hi ROHITJGC,

ROHITJGC

First they dont want check boxes but Enable and Disable Buttons , I saw on below site 

http://jameschambers.com/2012/07/bootstrapping-mvc-say-no-to-checkboxes/  but getting error

0x800a1391 – JavaScript runtime error: ‘$’ is undefined

Also  How to use ASP.net Web API to do the edits??????

For this error, you need to load the jQuery files.

About the issue of Web API, please post it to the
Web API
forum.

ROHITJGC

I have no idea about polling the server every 3 seconds what does this mean and How to append this information to a list

Please refer to:

# JavaScript Timing Events

http://www.w3schools.com/js/js_timing.asp

# jQuery.ajax()

http://api.jquery.com/jquery.ajax/

Best Regards

Starain

[RESOLVED]Problem with CheckBoxListFor in MVC

Hello Everyone, I am trying to use checkboxlistfor in mvc to generate checkboxes dynamically for my items.Below is the my View code for checkboxlistfor:

<table class="form-table">
<tr>
<td>
<label>Searchfor</label>
</td>
<td>
@Html.CheckBoxListFor(model => model.PostedSearchableObject.PostedIds,
model => model.AvailableObjectTypes,
objecttype => objecttype.Id,
objecttype => objecttype.Name,
model => model.SelectedObjectTypes,
Position.Horizontal) </td>

When I run the solution I can see all the items that I need to have a checkbox for (ex: item1, item2, item3), but the problem is there are no Check-boxes next to each item for the user to select them. they are just a simple labels without a check box.

Does anyone has any idea why I can’t see the check-boxes?

thanks. 

Hi Benjaminsh,

Thanks for your post.

Benjaminsh

but the problem is there are no Check-boxes next to each item for the user to select them. they are just a simple labels without a check box.

According to your requirement,I did a sample.please refer to the following sample:

controller:

 [HttpGet]
        public ActionResult demo1()
        {
            WebCSDBEntities db = new WebCSDBEntities();
            return View(db.tblCities);
        }
        [HttpPost]
        public string demo1(IEnumerable<tblCity> cities)
        {
            if (cities.Count(x => x.IsSelected_) == 0)
            {
                return "you have not selected any city";
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("You selected-");
                foreach (tblCity city in cities)
                {
                    if (city.IsSelected_)
                    {
                        sb.Append(city.Name_ + ",");
                    }
                }
                sb.Remove(sb.ToString().LastIndexOf(","),1);
                return sb.ToString();
            }
        }

view:

@model reflectDemo.Models.tblCity

@{
    ViewBag.Title = "tblCity";
}

@*<h2>tblCity</h2>*@
@Html.HiddenFor(x=>x.Id)
@Html.HiddenFor(x=>x.Name_)
@Html.CheckBoxFor(x=>x.IsSelected_)
@Html.DisplayFor(x=>x.Name_)
@model IEnumerable<reflectDemo.Models.tblCity>

@{
    ViewBag.Title = "demo1";
}



<div style="font-family:Arial">
    <h2>demo1</h2>
    @using (Html.BeginForm())
    {
        @Html.EditorForModel()
        <br />
        <input type="submit" value="submit" /> 
    }
    
</div>

It worked on my side.

More information,you can check this:

#ASP.Net MVC- How to implement CheckBoxList

http://besttechnologyblog.com/2014/05/04/asp-net-mvc-how-to-implement-checkboxlist/

Hope this can be helpful.

Best Regards,

Eileen

Thank you very much for the time you spend to reply this thread. I found out the problem was due to overriding a CSS class.

[RESOLVED]Master Detail Inline Editing

User is presented with an index of orders in the system.

User will click into an Order to edit.

The Edit page will be presented with Order detail at the top in edit mode.

The bottom will have a grid (currently using Telerik Kendo), with all the orderline items.

I will need to allow the user to perform inline-editing. which includes Dropdown boxes, and a checkbox which allow SELECT ALL to update in bulk.

eg. Select All orderlines to set status to COMPLETED.

How is this achieved in MVC, along with ViewModel patterns.

alphabeatsco

The bottom will have a grid (currently using Telerik Kendo), with all the orderline items.

I will need to allow the user to perform inline-editing. which includes Dropdown boxes, and a checkbox which allow SELECT ALL to update in bulk.

Kendo have this example for inline editing.

http://demos.telerik.com/kendo-ui/grid/editing-inline

And , if you search, you will find one with dropdown too in the documentation

Hi alphabeatsco,

Thanks for your post.

You can refer to ignatandrei’s reply, and you can try to use webgrid to implement it.Please refer to the following tutorial:

#Web Grid with Razor Engine,Paging and Customized Edit and Delete facility

http://jainbipin.blogspot.com/2011/04/aspnet-mvc-3-razor-engine-web-grid.html

Hope this can be helpful.

Best Regards,

Eileen

Is WebGrid out of the box component from Visual Studio?

alphabeatsco

Is WebGrid out of the box component from Visual Studio?

No