WEST FARGO, N.D. — Representative Kevin Cramer, who latched onto Donald J. Trump even before he was president and never let go, ousted North Dakota’s incumbent Democratic senator, Heidi Heitkamp, on Tuesday, flipping a key seat that was vital to Republican efforts to hold the Senate.

In an election that largely became a referendum on the president, voters here cast out the centrist Ms. Heitkamp, replacing an increasingly rare moderate voice in the Senate with a proud and fiercely conservative partisan.

Mr. Cramer’s win affirmed the state’s support for Mr. Trump, who swept North Dakota in 2016 with a 36-percentage-point margin of victory. Eager to defeat Ms. Heitkamp, considered the Democrats’ most vulnerable senator, the president rallied here three times in support of the congressman in an effort to energize the Republican base.