Proximo
Proximo

Reputation: 6531

MVC4 Pass Model from View to Controller

//Model
public class Car
{
   string name{get;set;}
   double speed {get;set;}
   //etc.
}

Basic model

//Controller
public ActionResult ModifyCar(Car c)
{
    c = GetAdditionalData(c.name, c.speed);
    return View(c);
}

So I'm making call to outside service to get additional data for car.

Below is the form which I'm really confused on. I am just going to write this in HTML.

But from here I'd like to take a basic empty model.. populate it then send to the controller for additional data.

//View
@model Car
<form id="carform" method="post" action="/Car/ModifyCar"> //Guessing
    <input id="carName"  /> //Somehow bind with @model.name
    <input id="carSpeed" /> //Somehow bind with @model.speed
    <input type="submit" /> //Somehow send the model to the controller
</form>

Sorry I'm not really good at the View part at all but I hope you can see where I was going here.

Also, I'm doing validation that requires a form id.. I noticed that there is no form id when using HTML Helper to make the form. Thats going to break my CSS I wrote.

Any help would be greatly appreciated.

Thanks

Upvotes: 0

Views: 529

Answers (1)

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

Try this :

@model Car
<form id="carform" method="post" action="/Car/ModifyCar"> //Guessing
<input id="carName" name="carName" [email protected]  /> //Somehow bind with @model.name
<input id="carSpeed" name="carSpeed" [email protected] /> //Somehow bind with @model.speed
<input type="submit" value="Submit" /> //Somehow send the model to the controller
</form>

when your form will submit it will go to ModifyCar action in Car Controller.

But as you has mentioned in your question that we cannot give id in html helper ,it is wrong we can for ex:

@using(Html.BeginForm("ModifyCar","Car",FormMethod.Post,new{ id="carform" }))

the above BeginForm() will render same html as:

<form id="carform" method="post" action="/Car/ModifyCar">

Upvotes: 1

Related Questions